gpt4 book ai didi

mysql - 为什么删除重复记录时出现 max(rowid) 或 min(rowid) ?

转载 作者:行者123 更新时间:2023-11-29 10:16:28 27 4
gpt4 key购买 nike

我们可以在不使用伪列rowid的情况下删除重复记录吗...删除重复记录时 max(rowid)/min(rowid) 的含义是什么?

最佳答案

ROWID 是 Oracle 用于定位物理记录的内部行标识符。因此,即使您的“ID”可能有重复的值,每个记录 ROWID 仍然是唯一的。

create table prices(
id varchar2(15) not null
,price number not null
,upd_date date not null
-- ,primary key(id)
);

ROWID ID PRICE UPD_DATE
------------------ -- ----- ----------
AChTgbADaAAFgxYAAA A 7 2018-04-10

AChTgbADaAAFgxYAAB B 8 2018-04-09
AChTgbADaAAFgxYAAC B 8 2018-04-09
AChTgbADaAAFgxYAAD B 8 2018-04-09

AChTgbADaAAFgxYAAE C 9 2018-04-06
AChTgbADaAAFgxYAAF C 8 2018-04-05
AChTgbADaAAFgxYAAG C 7 2018-04-04

组中的 MAX(rowid)通常是最近插入的记录,但这种假设在生产代码中经常是错误的。只能依靠它来删除完美的重复。完美的重复是 select unique * 产生一条记录的重复。对于所有其他用途,您需要一个鉴别器。鉴别器列可用于区分两个记录,例如使用指示修改时间的更新日期。

如果您使用典型的 ROWID 方法对我的示例表进行重复数据删除,您将错误地删除最新价格 9(如 upd_date 所证明的)。

delete
from prices
where rowid not in(
select max(rowid)
from prices
group by id);

更好的方法是首先使用鉴别器,然后作为最后的手段使用 ROWID。

delete 
from prices
where rowid in(
select rid
from (select rowid as rid
,row_number() over( -- Assign a sequence number
partition by id -- Group rows by ID
order by upd_date desc -- Sort them by upd_date first
,rowid desc -- Then by ROWID
) as rn
from prices
)
-- The most recent record will be rn = 1.
-- The second most recent record will be rn = 2, etcetera
where rn > 1 -- Select only the duplicates ("after" the most recent one record
);

关于mysql - 为什么删除重复记录时出现 max(rowid) 或 min(rowid) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50055154/

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