gpt4 book ai didi

postgresql - 删除具有重复次要值的行

转载 作者:行者123 更新时间:2023-11-29 13:06:38 25 4
gpt4 key购买 nike

对于任何 DBA 来说,这可能是一个垒球问题,但这是我的挑战。我有一个看起来像这样的表:

id     parent_id    active
--- --------- -------
1 5 y
2 6 y
3 6 y
4 6 y
5 7 y
6 8 y

我正在使用的系统的运行方式,每个父级应该只有一个事件行。因此,如果 ID #2 和 #3 处于事件状态 = 'n' 就可以了。

我需要运行一个查询来查找具有重复 parent_ids 的所有行,这些行都处于事件状态,并将除最高 ID 之外的所有行都翻转为 active = 'y'。

这可以在单个查询中完成,还是我必须为此编写一个脚本? (使用 Postgresql,顺便说一下)

最佳答案

ANSI 风格:

update table set
active = 'n'
where
id <> (select max(id) from table t1 where t1.parent_id = table.parent_id)

Postgres 特定的:

update t1 set
active = 'n'
from
table t1
inner join (select max(id) as topId, parent_id from table group by parent_id) t2 on
t1.id < t2.topId
and t1.parent_id = t2.parent_id

第二个可能要快一点,因为它没有为每一行做一个相关的子查询。享受吧!

关于postgresql - 删除具有重复次要值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com