首页 > 技术文章 > mysql删除重复数据

gqymy 2018-11-27 15:42 原文

先查询某字段重复的全部数据

select count(param) as count from table group by param having count > 1

(多个字段判断重复数据)

select count(param) as count1, count(param2) count2 from table group by param, param2 having count > 1 and count2 > 1

因为删除重复数据时肯定会保留一条,所以使用not in(not exists) 在重复数据中保留一条数据

select min(id) as id ,count(param) as count from table group by param having count > 1   //根据最大或最小值来进行数据保留

select count(param) as count from table where id not in (

select t.id from ( select min(id) as id ,count(param) as count from table group by param having count > 1  ) t

) group by param having count > 1

查询的sql已经写好,接下来就直接做删除操作

delete from table where id in 上面的sql

每次删除一个重复id,记得多执行几次

推荐阅读