开发者

Delete items from table without a reference ID

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜