【发布时间】:2016-12-13 12:11:41
【问题描述】:
我想做的是从table 1 中删除行,然后从table 2 中删除那些从table 1 中删除的行使用外键引用的行。我想知道是否可以在不必删除表 2 上的外键并使用 on delete cascade 重新创建它的情况下执行此操作。
我不擅长使用 SQL,尝试了 3 种不同的方法,但均未成功。
1:尝试一次从多个表中删除
delete from table1 a, table2 b where a.table2_id = b.id and a.column < 0;
2:删除并返回
delete from table2 where id in
(delete from table1 where column < 0 returning table2_id as id);
3:从select创建一个数组并用它从两个表中删除
DECLARE
arr integer[] := array(select table2_id from table1 where column < 0);
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
delete from table1 where table2_id = m;
delete from table2 where id = m;
END LOOP;
END
【问题讨论】:
标签: postgresql