如何删除重复行并保留第一行?
我犯了一个错误,并且有不需要的重复项。
我有一个包含 4 个关键字段的表。 A1
、k1
、k2
、k3
。
A1
是自增,主键。
k1
、k2
和 k3
的组合应该是唯一的,我必须在创建唯一索引之前删除重复的行。有些行有一个重复项,有些行有多个重复项。
SELECT CONCAT(k1, k2, k) AS dup_value
FROM myviews
GROUP BY dup_value
HAVING (COUNT(dup_value) > 1)
显示我需要处理的重复值。但现在我不知道如何保留一个并删除每个重复集的其余部分。
I made a mistake and I have unwanted duplicates.
I have a table with 4 key fields. A1
, k1
, k2
, k3
.
A1
is auto increment and the primary key.
the combination of k1
, k2
and k3
is supposed to be unique and I have to delete the duplicate rows before I create a unique index. Some rows have one duplicate, some have many.
SELECT CONCAT(k1, k2, k) AS dup_value
FROM myviews
GROUP BY dup_value
HAVING (COUNT(dup_value) > 1)
shows me duplicates values that I need to deal with. But now I don't know how to keep one and delete the rest of each duplicate set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有这样的事吗?
Someting like this?
您的 concat 函数中需要一个分隔符,因为否则“a”、“b”和“cd”与“abcd”、“”、“”相同。
You need a separator in your concat function, because otherwise "a", "b", and "cd" is the same as "abcd", "", "".
备份数据,然后...
MySQL 支持 DELETE 语句中的 JOIN。如果您想保留第一个重复项:
如果您想保留最后一个重复项:
Backup your data, then...
MySQL supports JOINs in DELETE statements. If you want to keep the first of the duplicates:
If you want to keep the last of the duplicates:
您可以创建一个具有相同结构但为空的新表,然后在其上创建唯一键,然后将原始表插入新表中。表,然后删除原来的表。
INSERT IGNORE
将自动忽略任何主要或唯一的关键问题,并仅跳过重复项。You can create a new table with the same structure but empty, then create the unique key on it, then do a
INSERT IGNORE
/SELECT * FROM
the original table into the new table, then delete the original table.INSERT IGNORE
will automatically ignore any primary or unique key issues and just skip the duplicates.