MySQL重複資料刪除記錄只保留一條

來源:互聯網
上載者:User

標籤:create   重複   publish   記錄   lis   blog   time   rom   span   

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

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);

 

但是我的需求不太一樣,


| 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);

 

MySQL重複資料刪除記錄只保留一條

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.