[英]How can I delete rows from table A and table B if rows in table B don't exist
I have 2 tables and I need to delete rows from both tables if A.itemID does not exist in table B我有 2 个表,如果表 B 中不存在 A.itemID,我需要从两个表中删除行
I've tried doing:我试过这样做:
DELETE a,b FROM A a, B b WHERE NOT EXISTS (SELECT * FROM B b WHERE b.cid= a.itemID ); DELETE a,b FROM A a, B b WHERE NOT EXISTS (SELECT * FROM B b WHERE b.cid= a.itemID );
But I cant get the error: Error Code: 1093. You can't specify target table 'b' for update in FROM clause但我无法得到错误:错误代码:1093。您不能在 FROM 子句中指定目标表'b'进行更新
All help is appreciated!感谢所有帮助!
I have the following tables:我有下表:
Table A
+--------+--------+-------------+
|catId | itemID | lastModified|
+--------+--------+-------------+
| 167262 | 678909 | 2017-10-01 |
| 167262 | 986785 | 2012-01-03 |
| 143210 | 456776 | 2018-04-30 |
| 143210 | 345676 | 2019-06-14 |
| 143210 | 010836 | 2016-03-09 |
| 379588 | 883567 | 2019-03-04 |
+--------+--------+-------------+
Table B
+--------+----------+-------+
| cid |locationid| Type |
+--------+----------+-------+
| 678909 | 1 | a |
| 986785 | 1 | a |
| 143210 | 2 | b |
| 883567 | 3 | a |
+--------+----------+-------+ ```
My resulting tables would be :
Table A
+--------+--------+-------------+
|catId | itemID | lastModified|
+--------+--------+-------------+
| 167262 | 678909 | 2017-10-01 |
| 167262 | 986785 | 2012-01-03 |
| 379588 | 883567 | 2019-03-04 |
Table B
+--------+----------+-------+
| cid |locationid| Type |
+--------+----------+-------+
| 678909 | 1 | a |
| 986785 | 1 | a |
| 883567 | 3 | a |
+--------+----------+-------+
I need to delete rows from both tables if A.itemID does not exist in table B如果表 B 中不存在 A.itemID,我需要从两个表中删除行
If the itemId
does not match, then there is no row in B
.如果itemId
不匹配,则B
中没有行。 So, you just need to delete in A
.所以,你只需要在A
中删除。 So:所以:
DELETE a FROM a
WHERE NOT EXISTS (SELECT 1
FROM B b
WHERE b.cid = a.itemID
);
You could also express your logic using a delete anti-join:您还可以使用删除反连接来表达您的逻辑:
DELETE a
FROM A a
LEFT JOIN B b ON b.cid = a.itemID
WHERE b.cid IS NULL;
To add to Gordon Linoff's answer (which helped me get to my solution) the following shows how to view the records that will be deleted before doing it:要添加到 Gordon Linoff 的答案(这帮助我找到了我的解决方案),下面显示了如何在执行此操作之前查看将被删除的记录:
To view the records that WILL be affected:查看将受到影响的记录:
SELECT TableA.ColumnName FROM TableA
WHERE NOT EXISTS
(SELECT 1 FROM TableB WHERE TableB.ColumnName = TableA.ColumnName);
To then delete the affected rows:然后删除受影响的行:
DELETE TableA FROM TableA
WHERE NOT EXISTS
(SELECT 1 FROM TableB WHERE TableB.ColumnName = TableA.ColumnName);
So, the only differences are change SELECT for DELETE and removing the ColumnName from after the SELECT word.因此,唯一的区别是将 SELECT 更改为 DELETE 并从 SELECT 单词之后删除 ColumnName。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.