SQL Delete Query

杀马特。学长 韩版系。学妹 提交于 2019-12-12 02:12:32

问题


I need to write an SQL script that selects one record in table1, then does a lookup in the remaining tables in the database. If it doesn't find the record, I need delete the record from table1. Anyone provide some sample script?


回答1:


One example

delete table1
where not exists (select 1 
                   from Table2 
                   where table1.SomeColumn = Table2.SomeColumn)
AND table1.SomeColumn = 5 --just an example, 

Leave the AND out if you want to delete all the rows from table 1 that do not exist in table 2

you can also use LEFT JOIN or NOT IN




回答2:


I have done things like this:

DELETE table1
  FROM table1
 WHERE table1.ID NOT IN (
       SELECT RefID FROM Table2
       UNION
       SELECT RefID FROM Table3
       ...
       )

Assuming RefID are FK's to table1.ID. Is this what you need?




回答3:


DELETE FROM Table1 WHERE id=10 AND NOT EXISTS (SELECT * FROM Table2 WHERE id=10);



回答4:


Very generally, (since you gave little details)

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


来源:https://stackoverflow.com/questions/2998128/sql-delete-query

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