簡體   English   中英

如何刪除表中具有 null 外鍵引用的所有行?

[英]How do I delete all rows in a table which have a null foreign key reference?

我有兩個表,A 和 B。A 有一個B_Id列,它引用表 B 的Id列。

表 A 中有許多行具有B_Id的值,但該值在表 B 的 ID 列表中的任何位置都不存在。

我想刪除所有這些特定的行。

我試過了

select * from A left join B on A.B_Id = B.Id where B.Id = null

但這根本不是 select 任何東西。 如何更改 select 以檢索我想要的行?

NOT EXISTS在腦海中:

select a.*
from a
where not exists (select 1 from b where b.id = a.b_id);

如果要刪除行,可以輕松地將其合並到delete中:

delete from a
    where not exists (select 1 from b where b.id = a.b_id);

但。 . . 您應該通過設置適當的約束來真正解決問題。 您似乎想要一個NOT NULL約束和一個FOREIGN KEY約束。

您需要where b.id is null而不是where b.id = null In SQL, nothing is equal to null (nor different than null ): to compare against null , you need special construct is [not] null .

我認為這更簡單地表達為not exists

select a.*
from a
where not exists (select 1 from b where b.id = a.b_id)

如果你想要一個delete語句:

delete from a
where not exists (select 1 from b where b.id = a.b_id)

您需要使用IS運算符,例如

select * from A left join B on A.B_Id = B.Id where B.Id is null

原因是 null 是未知的,並且語言不確定某物是否等於它。 正如 Gordon Linoff 已經指出的那樣,您也可以通過not exists來做到這一點。

無論您嘗試什么,請確保對您的表進行完整備份。

如果B_Id已經是foreign key並且為您的數據庫啟用了foreign key檢查,那么您可以安全地假設 B 中沒有對的每條記錄在 A 中都有一個B_Id為 null,這使得連接和檢查是否存在變得不必要。

您可以使用 select 刪除要刪除的數據

SELECT * FROM A
WHERE B_ID NOT IN (SELECT ID FROM B);

要刪除這些行,只需使用此

DELETE FROM A
WHERE B_ID NOT IN (SELECT ID FROM B);

暫無
暫無

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

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