postgresql - 如何重用使用“WITH”运算符声明的 Postgres 变量
问题描述
我需要从两个表中删除记录,但我无法一致地执行它,因为从第一个表中删除后,将没有数据要从第二个表中删除。我试过以下:
WITH person_ids AS(select person_id from application_person
where application_id in (select DISTINCT duplicate.id
from application duplicate inner join application application
on duplicate.document_id = application.document_id
where duplicate.modify_date < application.modify_date)),
delete from application_person where application_person.person_id in (select person_id from person_ids);
delete from person where id in (select person_id from person_ids);
对于 person_ids 的第二次调用,我有Query failed: ERROR: relation "person_ids" does not exist
我究竟做错了什么?谢谢。
解决方案
我究竟做错了什么?
您有两个单独的语句。person_ids
仅在第一个范围内,持续到分号。
你会想要使用
WITH duplicate_applications AS (
select DISTINCT duplicate.id
from application duplicate
inner join application application using (document_id)
where duplicate.modify_date < application.modify_date)
), deleted_persons AS (
delete from application_person
where application_id in (select application_id from duplicate_applications)
returning person_id
)
delete from person
where id in (select person_id from deleted_persons);
推荐阅读
- python - 抓取时出错:“ValueError:请求 url 中缺少方案”
- mysql - 选择所有,除非 MYSQL 中的特定单元格值
- azure - 通过 Azure 数据工厂访问托管在私有 IP 上的 Azure VM 中的 API
- java - 如何向querydsl Predicate添加比较器?
- javascript - CSS 视觉渲染在 JS 脚本完成之前不显示
- intellij-idea - Intellij - 更新后打开项目快捷方式停止工作
- tfs - TFS 2018 到 2019 升级因缺少版本 ID 而失败
- python - Django cron 未使用 crontab 运行
- ibm-midrange - 无法读取 as400 错误 SQL0204 中的表数据
- php - 在 WooCommerce 中的结帐和我的帐户之间同步时事通讯自定义复选框