SQL Delete Query
我需要编写一个SQL脚本,在table1中选择一个记录,然后在数据库的其余表中进行查找。 如果找不到记录,我需要从table1中删除记录。 有人提供一些示例脚本吗?
一个例子
1 2 3 4 5 | DELETE table1 WHERE NOT EXISTS (SELECT 1 FROM Table2 WHERE table1.SomeColumn = Table2.SomeColumn) AND table1.SomeColumn = 5 --just an example, |
如果要删除表1中表2中不存在的所有行,请保留AND
你也可以使用LEFT JOIN或NOT IN
我做过这样的事情:
1 2 3 4 5 6 7 8 | DELETE table1 FROM table1 WHERE table1.ID NOT IN ( SELECT RefID FROM Table2 UNION SELECT RefID FROM Table3 ... ) |
假设RefID是table1.ID的FK。 这是你需要的吗?
很一般,(因为你提供的细节很少)
1 2 3 4 5 6 7 8 9 | DELETE Table1 t1 WHERE [Criteria TO find table1 Record] AND NOT EXISTS(SELECT * FROM Table2 WHERE pk = t1.Pk) AND NOT EXISTS(SELECT * FROM Table3 WHERE pk = t1.Pk) AND NOT EXISTS(SELECT * FROM Table4 WHERE pk = t1.Pk) ... etc. FOR ALL other TABLES |
1 | DELETE FROM Table1 WHERE id=10 AND NOT EXISTS (SELECT * FROM Table2 WHERE id=10); |