我想删除另一个表中没有现有外键的所有行 例如:
table1
+----+-------+
|id | data |
+----+-------+
| 1 | hi |
+----+-------+
| 2 | hi |
+----+-------+
| 3 | hi |
+----+-------+
| 4 | hi |
+----+-------+
| 5 | hi |
+----+-------+
table2
+----+-------+
|a_id| data |
+----+-------+
| 1 | hi |
+----+-------+
| 20 | hi |
+----+-------+
| 3 | hi |
+----+-------+
| 40 | hi |
+----+-------+
| 5 | hi |
+----+-------+
查询将删除table2上ID为#20和40的行。
我需要这样做才能与table1和table2建立关系。
答案 0 :(得分:11)
DELETE table2
FROM table2
LEFT JOIN table1
ON table2.a_id = table1.id
WHERE table1.id IS NULL
答案 1 :(得分:4)
总之,有一些树方法可以删除多个表
NOT IN(SELECT ...)
- @someone(他已删除了答案)
Delete From Tab2 where ID not in (Select ID From Tab1)
LEFT JOIN
- @eggyal
DELETE table2
FROM table2 LEFT JOIN table1 ON table2.a_id = table1.id
WHERE table1.id IS NULL
NOT EXISTS
DELETE
FROM table2
WHERE NOT EXISTS (
SELECT 1
FROM table1
WHERE table1.id = table2.a_id
)
根据What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?,不同的RDBMS表现不同。