我需要编写一个SQL脚本,在table1中选择一条记录,然后在数据库的其余表中进行查找。如果找不到记录,我需要从table1中删除记录。有人提供一些示例脚本吗?
答案 0 :(得分:3)
一个例子
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)
我做过这样的事情:
DELETE table1
FROM table1
WHERE table1.ID NOT IN (
SELECT RefID FROM Table2
UNION
SELECT RefID FROM Table3
...
)
假设RefID是table1.ID的FK。这是你需要的吗?
答案 2 :(得分:1)
DELETE FROM Table1 WHERE id=10 AND NOT EXISTS (SELECT * FROM Table2 WHERE id=10);
答案 3 :(得分:1)
非常一般,(因为你提供的细节很少)
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