Forestil dig din tabel test
indeholder følgende data:
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
Så vi skal finde alle gentagne e-mails og slette dem alle, men det seneste id.
I dette tilfælde aaa
, bbb
og eee
gentages, så vi ønsker at slette ID 1, 7, 2 og 6.
For at opnå dette skal vi først finde alle de gentagne e-mails:
select email
from test
group by email
having count(*) > 1;
EMAIL
--------------------
aaa
bbb
eee
Så fra dette datasæt skal vi finde det seneste id for hver af disse gentagne e-mails:
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
Endelig kan vi nu slette alle disse e-mails med et id, der er mindre end LASTID. Så løsningen er:
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;
Jeg har ikke mySql installeret på denne maskine lige nu, men burde virke
Opdater
Ovenstående sletning virker, men jeg fandt en mere optimeret version:
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;
Du kan se, at den sletter de ældste dubletter, dvs. 1, 7, 2, 6:
select * from test;
+----+-------+
| id | email |
+----+-------+
| 3 | ccc |
| 4 | bbb |
| 5 | ddd |
| 8 | aaa |
| 9 | eee |
+----+-------+
En anden version er sletningen leveret af Rene Limon
delete from test
where id not in (
select max(id)
from test
group by email)