首页 > 解决方案 > 模拟 DELETE 外键检查

问题描述

有什么方法可以模拟运行 DELETE 查询时发生的外键检查?

就像您尝试删除在其他表中引用的对象一样,您在运行 DELETE 查询时会遇到错误。但是有没有办法查询某个表中某个行的所有“依赖项”?

标签: sqlpostgresql

解决方案


但是如果您想检查是否有对特定行的引用,您可以使用与所有引用的表连接的查询:

select m.pk 
       , case when max(t1.fk) is not null then 1  else 0 end "refrenced in t1"
       , case when max(t2.fk) is not null then 1  else 0 end "refrenced in t2"
from MainTable m
left join childtable1 t1
 on m.pk = t1.fk
left join childtable1 t2
 on m.pk = t2.fk
where m.pk = 10;
group by m.pk

如果要获取主表和所有子表的行:

select * 
from MainTable m
left join childtable1 t1
 on m.pk = t1.fk
left join childtable1 t2
 on m.pk = t2.fk
where m.pk = 10;

推荐阅读