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

來源:互聯網
上載者:User

標籤:rac   ora   date   net   AC   font   not   文章   sel   

 面試碰到一個MySQl的有趣的題目,如何從student表中重複資料刪除名字的行,並保留最小id的記錄?

很遺憾當時沒有做出來,回家搜尋了一番,發現利用子查詢的可以很快解決。

1、刪除表中多餘的重複記錄,重複記錄是username判斷,只留有id最小的記錄

delete from studentwhereusername in ( select username from studentgroup by username having count(username)>1)and id not in (select min(id) as id from studentgroup by username having count(username)>1 )

(上面這條語句在mysql中執行會報錯:

執行報錯:1093 - You can‘t specify target table ‘student‘ for update in FROM clause

原因是:更新資料時使用了查詢,而查詢的資料又做了更新的條件,mysql不支援這種方式。oracel和msserver都支援這種方式。

怎麼規避這個問題?

再加一層封裝,

delete from student whereusername in (select username from ( select username from student group by username having count(username)>1) a)and id not in ( select id from (select min(id) as id from student group by username having count(username)>1 ) b)

 注意select min(id) 後面要有as id.

其實還有更簡單的辦法(針對單個欄位):

delete from student whereid not in (select id from (select min(id) as id from student group by username) b);

 

拓展:

2、刪除表中多餘的重複記錄(多個欄位),只留有id最小的記錄

delete from student awhere (a.username,a.seq) in (select username,seq from (select username,seq from a group by username,seq having count(*) > 1)  t1)and id not in ( select id from (select min(id) from vitae group by username,seq having count(*)>1) t2)

參考文章:

6407280

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.