删除表中重复记录,只保留一条:
delete from 表名 where 字段ID in (select * from (select max(字段ID) from 表名 group by 重复的字段 having count(重复的字段) > 1) as b);
实例:
2.当想要为某一个表建立一个唯一索引,由于表中有重复记录而无法进行时,需要删除重复记录。
例表 dept
id_no id_name
100 'AAA'
101 'BBB'
102 'CCC'
103 'DDD'
100 'EEE'
100 'FFF'
103 'GGG'
请写一条(或一组)SQL语句,删除重复的行,但重复的行中需要保留一行,
如上表,id_no=100需要删除2行,保留一行,id_no=101需要删除一行保留一行id_no=102和103则不删
delete from dept where id_no not in ( select * from (select max(id_no) from dept group by id_no having count(id_no)>1) b);
以上转自http://flyer0126.iteye.com/blog/497359
但是我的需求不太一样,
| id | createTime | labId | pubId |
+—–+———————+——-+————————————–+
| 171 | 2014-05-22 21:49:11 | 1 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 172 | 2014-05-22 21:49:11 | 2 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 173 | 2014-05-22 21:49:11 | 6 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 174 | 2014-05-22 21:49:11 | 5 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 175 | 2014-05-22 21:49:11 | 2 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 176 | 2014-05-22 21:49:11 | 6 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 177 | 2014-05-22 21:49:11 | 5 | d4165953-2245-4b8c-b21d-8c08d519f66e |
| 178 | 2014-07-03 15:20:07 | 2 | d5308254-3b52-4ada-8e10-16b6a764c5e5 |
| 179 | 2014-07-03 15:36:00 | 2 | d4bc80b4-b57b-4049-9ab3-8f45102fae91 |
| 180 | 2014-07-04 21:05:26 | 4 | f8ccee8f-d93c-41cc-8d2f-28ada7ea4b07 |
我需要把labId和pubId相同的重复记录删掉,只要labId和pubId有一项不同就不算重复记录。
delete from t_publishandlabel where id not in ( select * from(select id from t_publishandlabel group by pubId,labId)b);
来自:http://my.oschina.net/u/565871/blog/287582