小编典典

如何删除重复的行并保留第一行?

mysql

我犯了一个错误,并且有多余的重复项。

我有一个包含4个关键字段的表。A1k1k2k3

A1 是自动递增和主键。

的组合k1k2k3应该是唯一的,我有我之前创建唯一索引来删除重复的行。有些行有一个重复项,有些行有很多重复项。

SELECT CONCAT(k1, k2, k) AS dup_value
  FROM myviews
 GROUP BY dup_value
HAVING (COUNT(dup_value) > 1)

向我显示了我需要处理的重复值。但是现在我不知道如何保留一个并删除每个重复集的其余部分。


阅读 680

收藏
2020-05-17

共1个答案

小编典典

备份数据,然后…

MySQL在DELETE语句中支持JOIN。如果要保留第一个重复项:

DELETE a
  FROM MYVIEWS a
  JOIN (SELECT MIN(t.a1) AS min_a1, t.k1, t.k2, t.k3
          FROM MYVIEWS t
      GROUP BY t.k1, t.k2, t.k3
        HAVING COUNT(*) > 1) b ON b.k1 = a.k1
                              AND b.k2 = a.k2
                              AND b.k3 = a.k3
                              AND b.min_a1 != a.a1

如果要保留最后一个重复项:

DELETE a
  FROM MYVIEWS a
  JOIN (SELECT MAX(t.a1) AS max_a1, t.k1, t.k2, t.k3
          FROM MYVIEWS t
      GROUP BY t.k1, t.k2, t.k3
        HAVING COUNT(*) > 1) b ON b.k1 = a.k1
                              AND b.k2 = a.k2
                              AND b.k3 = a.k3
                              AND b.max_a1 != a.a1
2020-05-17