簡體   English   中英

刪除表中沒有在另一個表中引用的所有記錄

[英]Delete all records in table which have no reference in another table

我有一個名為Document的表。

文件

id int
docuid int
doc blob

然后我有兩個引用表

AppRequiredDocuments

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

AppDocuments

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

我有一個非常舊的遷移文件表中的孤立項目,必須在其他表格中引用。 如何僅刪除文檔表中未在AppDocumentsAppRequriedDocuments引用的文檔?

一種方法使用刪除連接:

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記錄沒有被兩個輔助表中的任何東西引用,那么在連接的結果集中,這兩個其他表的docid應該是NULL

您可以使用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)

您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM