gpt4 book ai didi

MySQL删除重复记录但保持最新

转载 作者:IT老高 更新时间:2023-10-28 23:45:26 24 4
gpt4 key购买 nike

我有唯一的 idemail 字段。电子邮件被重复。我只想保留所有重复项的一个电子邮件地址,但要使用最新的 id(最后插入的记录)。

我怎样才能做到这一点?

最佳答案

想象你的表 test 包含以下数据:

  select id, email
from test;

ID EMAIL
---------------------- --------------------
1 aaa
2 bbb
3 ccc
4 bbb
5 ddd
6 eee
7 aaa
8 aaa
9 eee

所以,我们需要找到所有重复的邮件并将它们全部删除,但最新的id。
在这种情况下,aaabbbeee 是重复的,所以我们要删除 ID 1、7、2 和 6。

要做到这一点,首先我们需要找到所有重复的电子邮件:

      select email 
from test
group by email
having count(*) > 1;

EMAIL
--------------------
aaa
bbb
eee

然后,从这个数据集中,我们需要为这些重复的电子邮件中的每一个找到最新的 id:

  select max(id) as lastId, email
from test
where email in (
select email
from test
group by email
having count(*) > 1
)
group by email;

LASTID EMAIL
---------------------- --------------------
8 aaa
4 bbb
9 eee

最后,我们现在可以删除所有这些 ID 小于 LASTID 的电子邮件。所以解决办法是:

delete test
from test
inner join (
select max(id) as lastId, email
from test
where email in (
select email
from test
group by email
having count(*) > 1
)
group by email
) duplic on duplic.email = test.email
where test.id < duplic.lastId;

我现在没有在这台机器上安装 mySql,但应该可以工作

更新

上面的delete可行,但我找到了一个更优化的版本:

 delete test
from test
inner join (
select max(id) as lastId, email
from test
group by email
having count(*) > 1) duplic on duplic.email = test.email
where test.id < duplic.lastId;

您可以看到它删除了最旧的重复项,即 1、7、2、6:

select * from test;
+----+-------+
| id | email |
+----+-------+
| 3 | ccc |
| 4 | bbb |
| 5 | ddd |
| 8 | aaa |
| 9 | eee |
+----+-------+

另一个版本,是 Rene Limon 提供的删除

delete from test
where id not in (
select max(id)
from test
group by email)

关于MySQL删除重复记录但保持最新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107167/

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