如何从表中删除然后删除引用的已删除行? (PostgreSQL系统)

时间:2016-12-13 12:11:42

标签: postgresql

我想要做的是从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

2 个答案:

答案 0 :(得分:2)

您可以使用可写CTE在单个语句中执行此操作

with t1_deleted as (
   delete from table1 where column < 0 
   returning table2_id as id
)
delete from table2 
where id in (select id from t1_deleted);

答案 1 :(得分:1)

如果你可以重新安排删除,我认为你可以这样做。

请尝试以下更新功能。

create table schema_name.table_name1 (id serial primary key, name text)
create table schema_name.table_name2(id bigint references schema_name.table_name1(id), mno bigint)

create or replace function schema_name.fn_test_f_k() returns void as $$
DECLARE
   c1 cursor for select id from schema_name.table_name1 where id = 1;
BEGIN
   for r IN c1
   LOOP
      delete from schema_name.table_name2 where id = r.id;
      delete from schema_name.table_name1 where id = r.id;
   END LOOP;
END
$$
LANGUAGE PLPGSQL SECURITY DEFINER;

select schema_name.fn_test_f_k();