删除另一个表中没有id的所有行

时间:2013-12-09 03:00:39

标签: mysql sql database-relations

我想删除另一个表中没有现有外键的所有行 例如:

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建立关系。

2 个答案:

答案 0 :(得分:11)

DELETE table2 
FROM   table2 
       LEFT JOIN table1 
              ON table2.a_id = table1.id 
WHERE  table1.id IS NULL 

答案 1 :(得分:4)

总之,有一些树方法可以删除多个表

  1. NOT IN(SELECT ...) - @someone(他已删除了答案)

    Delete From Tab2 where ID not in (Select ID From Tab1)
    
  2. LEFT JOIN - @eggyal

    DELETE table2
    FROM   table2 LEFT JOIN table1 ON table2.a_id = table1.id
    WHERE  table1.id IS NULL
    
  3. NOT EXISTS

    DELETE
    FROM  table2
    WHERE NOT EXISTS (
      SELECT 1
      FROM table1
      WHERE table1.id = table2.a_id
    )
    
  4. 根据What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?,不同的RDBMS表现不同。