删除查询根据复杂条件查找记录不起作用

问题描述 投票:0回答:2

我有一个如下结构的 postgres 表

我想编写一个查询,从表中删除所有超过 90 天且处于 COMPLETE 状态的记录。如果任何行具有 root_id 或parent_id 并且是OPEN,则不应删除root_id 和parent_id 行。在上表中,应删除 id=1 的行。虽然 id=2 和 id=3 是完整的并且超过 90 天,但由于 id=4 具有 root_id,parent_id 具有 2 和 3,因此所有 3 行(id=2、id=3 和 id=4)应该不被删除。 我尝试了多种内部查询方法,但我无法为这种情况编写查询。

java sql postgresql query-optimization amazon-aurora
2个回答
0
投票

将您的需求翻译成 SQL,我明白了

DELETE FROM tab
WHERE status = 'COMPLETE'
  AND timestamp < current_timestamp - INTERVAL '90 days'
  AND NOT EXISTS (SELECT 1 FROM tab AS t2
                  WHERE t2.status = 'OPEN'
                    AND (tab.id = t2.root_id OR tab.id = t2.parent_id)
                 );

0
投票

首先识别记录

id
-s 是具有“OPEN”状态的记录的父级或根,并将它们存储在
t
CTE 中,然后删除那些“COMPLETE”、超过 90 天且其
id
为不在
t
ts = 'older than 90 days'
是说明性的。

with t (id) as 
(
 select unnest(array[root_id, parent_id])
 from the_table 
 where status = 'OPEN' 
  and root_id is not null 
  and parent_id is not null
)
delete from the_table
where status = 'COMPLETE'
  and ts = 'older than 90 days'
  and id not in (select id from t);

DB-fiddle 演示

© www.soinside.com 2019 - 2024. All rights reserved.