Delete all rows which has no id existing in another table

帅比萌擦擦* 提交于 2019-11-29 11:05:25
eggyal
DELETE table2 
FROM   table2 
       LEFT JOIN table1 
              ON table2.a_id = table1.id 
WHERE  table1.id IS NULL 
Jason Heo

To sum up, there are tree ways to delete multi tables

  1. NOT IN(SELECT ...) - @someone (he had deleted his answer)

    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
    )
    

According to What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?, different RDBMS perform differently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!