从表中删除没有引用ID的项目

时间:2011-02-23 00:44:03

标签: sql

我需要删除所有没有分配许可证的贡献者

Table        : Columns

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

像这样的东西

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

我相信如果您使用SQL Server,这将有效:

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

在实际执行删除之前要做的一个很好的测试是将DELETE Contributors行替换为SELECT *。这将显示即将删除的所有记录,因此这是一个很好的理智检查...

所以你的理智检查看起来像这样:

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

答案 2 :(得分:1)

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