如何删除comparison表中与comparison_2表Barcodes匹配的行?
删除匹配子集中的行:SQL解决方案
Got it, let's tackle this problem. You need to delete rows from the comparison table where the Barcodes value matches any entry in the comparison_2 table (a smaller subset of comparison). Here are a couple of reliable approaches depending on your database:
方法1:使用JOIN进行删除
这种写法在MySQL、SQL Server等多数数据库中都能正常工作,执行效率通常也不错——尤其是当两张表都在Barcodes列上建了索引的时候:
DELETE c FROM comparison c INNER JOIN comparison_2 c2 ON c.Barcodes = c2.Barcodes;
我们给两张表起了短别名c和c2来简化语句,通过INNER JOIN精准定位到两张表中Barcodes匹配的行,然后只删除comparison表(别名c)中的对应记录。
方法2:使用子查询(兼容性更广)
如果你的数据库对JOIN式DELETE支持有限,或者你更习惯子查询的写法,这个方案几乎适用于所有关系型数据库:
DELETE FROM comparison WHERE Barcodes IN (SELECT Barcodes FROM comparison_2);
子查询会先提取comparison_2中所有的Barcodes值,然后删除comparison表中Barcodes落在这个值集合里的所有行。
关键提醒
执行删除操作前一定要先验证! 你可以先用SELECT语句确认要删除的行是不是你预期的:
SELECT * FROM comparison WHERE Barcodes IN (SELECT Barcodes FROM comparison_2);
毕竟删除操作是不可逆的,最好先备份目标表或者在测试环境先跑一遍,避免误删数据。
内容的提问来源于stack exchange,提问作者Hard work
相关产品推荐
相关产品推荐

