开发者

Delete items from table without a reference ID

开发者 https://www.devze.com 2023-02-12 13:59 出处:网络
I need to delete all 开发者_Python百科the Contributors that don\'t have a License assigned to them

I need to delete all 开发者_Python百科the Contributors that don't have a License assigned to them

Table        : Columns

Contributors : [id, Name,...]
Licenses     : [id, ContributorId, Name, ...]

Something like this

DELETE FROM Contributors
WHERE
License.ContributorId != Contributor.Id


DELETE FROM Contributors
WHERE NOT EXISTS (
  SELECT *
  FROM License
  WHERE License.ContributorId = Contributors.Id)


I believe this will work if you are using SQL Server:

DELETE Contributors 
FROM Contributors as c
LEFT JOIN License as l
ON c.id = l.ContributorID
WHERE l.id is null

A good test to do before actually doing the delete is to replace the DELETE Contributors line with SELECT *. This will show you all the records that are about to be deleted, so it's a nice sanity check...

So your sanity check would look like this:

SELECT *
FROM Contributors as c
LEFT JOIN License as l
ON c.id = l.ContributorID
WHERE l.id is null


 DELETE FROM Contributors
    WHERE Contributors.Id NOT IN 
    (SELECT DISTINCT License.ContributorId FROM License)
0

精彩评论

暂无评论...
验证码 换一张
取 消