删除重复的旧行并保留最新的mysql

时间:2013-04-30 17:55:58

标签: php mysql database

我有一张桌子

id:name:passportnumber:score
1:xxx:123456:99
2:yyy:789012:88
3:xxx:123456:11
4:xxx:123456:44
5:xxx:123456:66
6:xxx:123456:77

我想删除重复的旧行,只保留最新的具有相同护照号的行

id:name:passportnumber:score    
2:yyy:789012:88
6:xxx:123456:77

没有临时表的最佳方法是什么

由于

2 个答案:

答案 0 :(得分:6)

您应该可以对表进行自我加入并执行删除:

delete t1
from yt t1
inner join yt t2
  on t1.passportnumber = t2.passportnumber
where t1.id < t2.id;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

LEFT JOIN上的DELETE可以执行此操作;

DELETE Table1 FROM Table1
LEFT JOIN Table1 b
  ON Table1.id<b.id 
 AND Table1.passportnumber=b.passportnumber
WHERE b.id IS NOT NULL;

An SQLfiddle to test with