sql - 如何删除表中具有空外键引用的所有行?
问题描述
我有两个表,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
但这根本没有选择任何东西。如何更改选择以检索我想要的行?
解决方案
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
约束。
推荐阅读
- javascript - 意外的令牌 < 在 JSON 中的位置 0 用 firebase auth 表示
- docker - Docker NodeRed 提交的容器不维护流和模块
- android - 是否可以在没有 constrainSetStart 的情况下定义运动场景转换?
- javascript - 为什么条形图出现“反转值”?d3.js
- ruby - Vagrant 创建虚拟机,但突然将其销毁:(
- javascript - 选中单选按钮时的颜色操作
- button - 带有自定义字段的 Paypal 按钮
- laravel - 延长 Laravel 会话时间
- node.js - 强制 node-qrcode 在脚本结束之前将数据放入 PNG 文件中
- python - 在python中,如何将数组参数传递给powershell脚本