首页 > 解决方案 > Postgres 中的级联删除:从子表和父表中删除,并从子表中保存 ID

问题描述

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

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

第一步是从满足标准的 PARTICIPANTS_T 中删除,例如

delete from PARTICIPANTS_T where VALID_FLAG = 'Y';

第二种是从 USERS_T 中删除之前删除中引用了其 ID 的行。

delete from USERS_T where ID = [..from Step 1..]

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

我考虑过保存一个变量: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');

但这很不方便,因为它user_ids变成了需要维护的单独表。我上面的语法不正确。任何人都可以通过这两个步骤给出完整的可重复脚本吗?

标签: sqlpostgresql

解决方案


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

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;

推荐阅读