假设您的表 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。
在这种情况下,aaa、bbb 和 eee 是重复的,所以我们要删除 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)