sql - 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
变成了需要维护的单独表。我上面的语法不正确。任何人都可以通过这两个步骤给出完整的可重复脚本吗?
解决方案
这有效:围绕级联删除开始/提交:
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;
推荐阅读
- tree - 如何避免 pysimpleGUI 树(Tk 树?)中的重复父级
- apache-flink - 会话窗口如何在事件时间合并多流?
- excel - 更新 SUMIF 公式以支持过滤数据
- sql - 我正在寻找使用子查询中的值的方法
- scala - Scala 将 DF 转换为 RDD - 错误 java.lang.NumberFormatException:对于输入字符串:“age”
- python - 增量分析中的特征缩放
- css - 为什么我的第二个延迟的 CSS 动画把一切都搞砸了?
- java - 具有替代合并功能的合并排序的时间复杂度
- typescript - TypeScript:为什么这里有一个 `keyof` 可以解决这个问题
- python - 列表到嵌套列表和字典