Sql 如何选择Postgres中父表中不存在的外键行?

Sql 如何选择Postgres中父表中不存在的外键行?,sql,postgresql,select,foreign-keys,Sql,Postgresql,Select,Foreign Keys,表2: id (pk) table1_id (fk) other_columns 表1: id (pk) other_columns 表1记录已删除,但表2参考文献仍保留,且未作废。如何最好地从表2中查询选择表1中不存在的外键的列表?您可以使用不存在: select t2.* from table2 t2 where not exists (select 1 from table1 t1 where t1.id = t2.table1_id) select t2.* from table2

表2:

id (pk)
table1_id (fk)
other_columns
表1:

id (pk)
other_columns

表1记录已删除,但表2参考文献仍保留,且未作废。如何最好地从表2中查询选择表1中不存在的外键的列表?

您可以使用
不存在

select t2.*
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.table1_id)
select t2.*
from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.pk = t2.fk
                 );
您可以轻松地将其转换为
delete
语句:

delete from table 2
where not exists (select 1 from mytable where t1.id = t2.table1_id)

如果您有级联外键约束,这将不是一个问题。但您可以使用
不存在

select t2.*
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.table1_id)
select t2.*
from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.pk = t2.fk
                 );