MYSQL刪除重複記錄(此處有正解)

刪除表中重複記錄,只保留一條:java

delete from 表名 where 字段ID in (select * from (select max(字段ID) from 表名 group by 重複的字段 having count(重複的字段) > 1) as b);ide

實例:
2.當想要爲某一個表創建一個惟一索引,因爲表中有重複記錄而沒法進行時,須要刪除重複記錄。
例表 dept.net

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則不刪blog

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/497359it

可是個人需求不太同樣,
| 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/287582class

相關文章
相關標籤/搜索