删除 table 中在另一个 table 中没有引用的所有记录

Delete all records in table which have no reference in another table

我有一个 table 叫做 Document

文档:

id int
docuid int
doc blob

然后我有两个引用 tables

AppRequiredDocuments:

id int
appid int
docid int -> references document -> id

AppDocuments:

id int
appid int
docid int -> references document -> id

由于非常老的迁移,文档 table 中的孤立项必须在其他 table 中引用。如何只删除文档 table 中未在 AppDocumentsAppRequriedDocuments 中引用的文档?

您可以使用 NOT EXISTS 查找和删除这些项目:

delete from document d
where not exists (select 1 from AppRequiredDocuments a where a.docid = d.id);
and not exists (select 1 from AppDocuments a where a.docid = d.id);

一种方法使用删除连接:

DELETE d
FROM Document d
LEFT JOIN AppRequiredDocuments t1
  ON d.id = t1.docid
LEFT JOIN AppDocuments t2
  ON d.id = t2.docid
WHERE t1.docid IS NULL AND
      t2.docid IS NULL

这里的逻辑是,如果给定的Document记录没有被两个辅助表中的anything引用,那么在join的结果集中docid 其他两个表的列应该 bothNULL.

您可以使用 union [all] 运算符生成单列引用,然后对其进行检查,例如,使用 [not] exists 运算符:

DELETE FROM Document d
WHERE  NOT EXISTS (SELECT *
                   FROM   AppRequiredDocuments ard
                   WHERE  ard.docid = d.id
                   UNION ALL
                   SELECT *
                   FROM   AppDocuments ad
                   WHERE  ad.docid = d.id)