How to delete duplicate records in mysql database?的副本
id | name | link
1 bla www.google.com
2 lal www.stackoverflow.com
3 afs www.google.com
4 sds www.microsoft.com
在我的数据库中有一些行具有相同的链接。我想删除其中一行具有相同链接。
例如,在我的示例中,我想删除id=3的行,但我想保留id=1。
我该怎么做?
顺便说一下,有5840排。我不知道哪一个是一样的。我需要一个代码来比较它们
最佳答案
诀窍是通过比较id来保持最新值
DELETE FROM table_name t1, table_name t2 WHERE t1.name = t2.name and t1.link = t2.link and t1.id < t2.id
这只是一个想法,这是我的Oracle环境中的一个功能齐全的示例(我已经有几周没有使用DB了,所以我正在尝试最小化查询,抱歉)
SQL> select * from dup;
ID STH STH2
---------- ---------- ----------
1 45 45
2 45 56
3 45 45
4 14 56
5 14 56
DELETE FROM dup where id in (SELECT DISTINCT t1.id FROM dup t1, dup t2 WHERE t1.sth = t2.sth and t1.sth2 = t2.sth2 and t1.id < t2.id);
SQL> select * from dup;
ID STH STH2
---------- ---------- ----------
2 45 56
3 45 45
5 14 56