首页 > 解决方案 > 如何删除表中具有空外键引用的所有行?

问题描述

我有两个表,A 和 B。A 有一列B_Id引用Id表 B 的列。

表 A 中有许多行的值为B_Id,但该值在表 B 的 Id 列表中的任何位置都不存在。

我想删除所有这些特定的行。

我试过了

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

但这根本没有选择任何东西。如何更改选择以检索我想要的行?

标签: sqlsql-servertsql

解决方案


NOT EXISTS想到:

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

delete如果要删除行,可以轻松地将其合并到 a中:

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

但 。. . 您应该通过设置适当的约束来真正解决问题。你似乎想要一个NOT NULL约束和一个FOREIGN KEY约束。


推荐阅读