【发布时间】:2020-01-08 02:37:04
【问题描述】:
表2:
id (pk)
table1_id (fk)
other_columns
表1:
id (pk)
other_columns
表 1 记录已被删除,但表 2 引用仍然存在并且未被取消。您如何最好地从表 2 中查询选择表 1 中不存在的外键的列表?
【问题讨论】:
标签: sql postgresql select foreign-keys
表2:
id (pk)
table1_id (fk)
other_columns
表1:
id (pk)
other_columns
表 1 记录已被删除,但表 2 引用仍然存在并且未被取消。您如何最好地从表 2 中查询选择表 1 中不存在的外键的列表?
【问题讨论】:
标签: sql postgresql select foreign-keys
你可以使用not exists:
select t2.*
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.table1_id)
您可以轻松地将其转换为delete 声明:
delete from table 2
where not exists (select 1 from mytable where t1.id = t2.table1_id)
【讨论】:
如果您有级联外键约束,这将不是问题。但是你可以使用not exists:
select t2.*
from table2 t2
where not exists (select 1
from table1 t1
where t1.pk = t2.fk
);
【讨论】: