【问题标题】:Delete all rows which has no id existing in another table删除另一个表中不存在 id 的所有行
【发布时间】:2013-12-26 01:48:35
【问题描述】:

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

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

【问题讨论】:

  • Delete From Tab2 where ID not in (Select ID From Tab1)?

标签: mysql sql database-relations


【解决方案1】:
DELETE table2 
FROM   table2 
       LEFT JOIN table1 
              ON table2.a_id = table1.id 
WHERE  table1.id IS NULL 

【讨论】:

    【解决方案2】:

    总结一下,删除多表有tree方式

    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
      )
      

    根据What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?,不同的RDBMS表现不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2015-07-23
      • 2021-09-28
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多