从MYSQL表中删除第一个重复项

9

我的表中有511个重复项,我需要删除这些项,但不删除原始项。因此,我想删除每个重复项的每二次出现。

我该如何做到这一点?

表格:

code  /   status  /   time
E3F4FF928A  /  0 /
07D95444BB  /  0 /  
07D95444BB /   0 / 
40006C128F  / 0  / 1315293012
2B45790E52   /  0  /
40006C128F  / 0  / 1315293012

请发布您的表定义。 - Jeremy Holovacs
1
它们是完全重复的,还是你在其中某个地方有一个唯一键? - Jason
1
真正的副本是原始数据的完全复制。你是否真的有副本,还是有许多数据相同但自增列或创建日期等内容不同的行? - Zak
你需要提供表结构(列)以及一些示例数据。 - BlackTigerX
已删除 已删除 - Jake
3个回答

8

不涉及“我想删除每个重复项的每个第二次出现。” - The Scrum Meister
是的,这并没有达到预期的结果。 - Jeremy Holovacs
1
请更具体一些,你有一个 b a b c b a 的序列。你是想要得到 a b c 还是 a b c b a? - Zak
实际上,MySql 文档 指定:仅使用具有唯一键重复的第一行。其他冲突行将被删除 - The Scrum Meister
+1,我喜欢这个答案。你可能需要一个复合索引,只需将额外的字段添加到索引unique index (col1, col2, col3)中即可。 - Johan
显示剩余2条评论

7
今天我遇到了一个问题(在表中没有唯一的键)。我是这样解决的:
DELETE FROM table where code=x and status=y and time=z LIMIT 1;

这将删除符合给定条件的第一行(如果您有n个重复项,则将n-1放入以仅保留一个)。


1
不要解释它。 - chuse

0
DELETE t2 FROM table1 t2 
INNER JOIN table1 t1 ON 
      (t1.somefield = t2.somefield 
   AND t1.otherfield = t2.otherfield   /*add more fields if need be */
   AND t2.id > t1.id)
LEFT JOIN table1 t3 ON 
      (t1.somefield = t3.somefield 
   AND t1.otherfield = t3.otherfield   /*add more fields if need be */
   AND t3.id > t2.id) 
WHERE (t3.id IS NULL)  
ORDER BY t2.id ASC

这应该只删除第二个重复项,保留第三个及以后的重复项。

如果您想要更简单的方法,并且您有一个时间戳列,也许您想要执行以下操作:

DELETE t2 FROM table1 t2 
INNER JOIN table1 t1 ON 
      (t1.somefield = t2.somefield 
   AND t1.otherfield = t2.otherfield   /*add more fields if need be */
   AND t2.`timestamp` > t1.`timestamp`)
WHERE (1=1)        /*In some mode(s) MySQL requires a where clause with delete*/
ORDER BY t2.id ASC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接