mysql中查找并删除重复数据

mysql version5.1

1-查找某一列(例如idcode)重复的数据, 从worker_back表中找到idcode数据有重复的

select * from worker_back group by idcode having count(idcode) > 1;

2-删除重复的数据,只保留id最小的数据

2.1 常见的写法

delete from worker_back
where idcode  in ( select idcode from worker_back group by idcode having(idcode) > 1 )
and wid not in ( select min(wid) from worker_back group by idcode having(idcode) > 1 );
此种 写法是错误的, 因为in 后面要跟一组数据, 而子查询返回的数据类型和它对应不上, 所以应该将子查询的结果当做一个表, 从其中再讲那列数据取出来即可. 

正确写法(亲测可用):

delete from worker_back
where idcode  in (select wb.idcode from (select idcode from worker_back group by idcode having(idcode) > 1) as wb)
and wid not in (select w.ids from(select min(wid) as ids from worker_back group by idcode having(idcode) > 1) as w );



你可能感兴趣的:(mysql)