MySQL删除重复记录并且只保留一条

一张表某个字段存在重复记录想删除重复数据保留一条

DELETE
FROM
    pet_order
WHERE
    name IN (
        SELECT
            t.name
        FROM
            (
                SELECT
                    name
                FROM
                    pet_order
                GROUP BY
                    name
                HAVING
                    count(1) > 1
            ) t
    )
AND id NOT IN (
SELECT
    dt.mindeptno
FROM
    (
        SELECT
            min(id) AS mindeptno
        FROM
            pet_order
        GROUP BY
            name
        HAVING
            count(1) > 1
    ) dt
)


大概原理:DELETE删除数据WHERE 嵌套一个SELECT查询重复的数据,AND NOT IN 目的是保留一条,AND里面也是SELECT查询重复数据最小的id。


最后只需要把pet_order 换成你的表名,name换成你要去重的字段即可


执行SQL之前(2条name为看车狗的重复数据,1条Pasa吴)



执行SQL之后(1条name为看车狗,1条Pasa吴)

2019年2月26日15:47:46上网无意发现另外一个更简洁的方法记录一下

DELETE from TableName WHERE (name) in   
(SELECT name from (SELECT name FROM TableName GROUP BY name HAVING COUNT(*)>1) s1)   
AND  
id NOT in (SELECT id from (SELECT id FROM TableName GROUP BY name HAVING COUNT(*)>1) s2); 
#把TableName换成你的表名,name换成你要去重的字段

第一个SQL执行时间
受影响的行: 6
时间: 0.008s

第二个SQL执行时间
受影响的行: 6
时间: 0.006s

Pasa吴技术博客
请先登录后发表评论
  • latest comments
  • 总共0条评论