gpt4 book ai didi

mysql - 在同一表中复制数据时排除特定行的插入

转载 作者:行者123 更新时间:2023-11-29 12:13:51 25 4
gpt4 key购买 nike

我使用下面的代码在 mysql 的同一个表中复制和插入数据:

INSERT INTO table (product_id, value, branch_id)
SELECT product_id, value, "71"
FROM table
WHERE branch_id = "53"

它非常适合复制和插入所有数据。在本例中,它复制branch_id=53的行,为每个复制的行添加新行,并且插入71而不是53branch_id。

但是现在我已经插入了一些branch_id=71的行,所以我需要通过声明类似WHEREbranch_id =“53”ANDproduct_id!=“product_id已经存在于行中来排除现有数据的插入Branch_id=71"

如何在 MySQL 中做到这一点?

最佳答案

如果(product_id,branch_id)上有唯一的复合索引,则可以使用INSERT IGNORE。然后,如果它尝试创建重复行,它只会默默地跳过该条目。

如果没有,你可以这样做:

INSERT INTO table (product_id, value, branch_id)
SELECT t1.product_id, t1.value, '71'
FROM table AS t1
LEFT JOIN table AS t2 ON t1.product_id = t2.product_id AND t2.branch_id = '71'
WHERE t1.branch_id = '53' AND t2.product_id IS NULL

关于mysql - 在同一表中复制数据时排除特定行的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com