Deleting orphans from a table

你说的曾经没有我的故事 提交于 2019-12-03 16:44:24

try this:

DELETE  FROM        table1
WHERE NOT EXISTS (SELECT NULL FROM table2 WHERE table1.ID = table2.ID)

If you want to use the same syntax, here is how it could have been:

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

Table 1 should then be the Child Table containing the orphaned records. And Table 2 the parent table.

    DELETE ChildTable  
    FROM Table1 ChildTable    
    LEFT JOIN Table2 ParentTable 
    ON ChildTable.id = ParentTable.id 
    WHERE ParentTable.id IS NULL 

A really helpful article. SQL JOINs make it easy to find and fix missing data

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