如何重用使用 'WITH' 运算符声明的 Postgres 变量

How to reuse Postgres variables declared using 'WITH' operator

我需要从两个 table 中删除记录,但我无法始终如一地执行它,因为从第一个 table 中删除后,第二个中将没有要删除的数据。 我试过以下:

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

我做错了什么? 谢谢

What am i doing wrong?

您有两个单独的语句。 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);