如果表b中的行不存在,如何删除表a和表b中的行

llycmphe  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(359)

我有两个表,如果表b中不存在a.itemid,我需要从两个表中删除行
我试过做:
从不存在的a,b中删除a,b(从b中选择*,其中b.cid=a.itemid);
但我不能得到错误:错误代码:1093。不能在from子句中为update指定目标表“b”
感谢您的帮助!
我有以下表格:

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     |
+--------+----------+-------+
kgqe7b3p

kgqe7b3p1#

如果表b中不存在a.itemid,我需要从两个表中删除行
如果 itemId 不匹配,则中没有行 B . 所以,你只需要删除 A . 所以:

DELETE a FROM a
    WHERE NOT EXISTS (SELECT 1
                      FROM B b
                      WHERE b.cid = a.itemID
                     );
jw5wzhpr

jw5wzhpr2#

您还可以使用delete-anti-join来表达您的逻辑:

DELETE a
FROM A a
LEFT JOIN B b ON b.cid = a.itemID
WHERE b.cid IS NULL;

相关问题