在Postgres中进行级联删除:从子级和父级表中删除,并从子级中保存ID

时间:2018-12-17 16:48:59

标签: sql postgresql

在Postgres中,我有两个表,需要使用Cascade Delete清除一些数据:

CRAN

第一步是从PARTICIPANTS_T中删除满足条件的信息,例如

- PARTICIPANTS_T: has a foreign key USER_ID on USERS_T.ID - USERS_T

第二个是从USERS_T中删除其ID在先前的Delete中引用的行。

delete from PARTICIPANTS_T where VALID_FLAG = 'Y';

如何在Postgres中进行级联删除?

我已经考虑过保存变量:delete from USERS_T where ID = [..from Step 1..]

select INTO

但这很不方便,因为if exists drop table user_ids; --This syntax is wrong select id into user_ids from users_t where id in ( select user_id from participants_t where valid_flag = 'Y');成为需要维护的单独表。我上面的语法不正确。有人可以通过这两个步骤给出完整的可重复脚本吗?

1 个答案:

答案 0 :(得分:0)

这有效:围绕级联删除开始/提交:

begin;
delete from participants_t where valid_flag = 'Y';
delete from users_t where id in (
            select user_id from participants_t where valid_flag = 'Y');       
commit;