mysql 刪除相同數據

最近在研究sql優化,設計到刪除重複信息時,遇到些小問題,網上查了些資料,在此記錄一下;

             user表
id  username  password
1   admin        123456
2   admin         654321
3   tom            123456

-- 根據某一字段(username),查詢全部重讀記錄
select * from user where username in(select username from user group by username having Count(*)>=2)

結果:
id   username  password
1    admin        123456
2    admin         654321


-- 篩選重複記錄(只顯示一條,相同記錄保留id的最小值)
select * from user where id not in(select max(id)  from user group by username having count(*)>=2)

結果:
id   username  password
1    admin        123456
3    tom            123456


-- 刪除全部重複記錄(只保留一條,id最小的)
delete from user where  id in (select id from (select max(id) id from user group by username having count(*)>=2) as u)

-- 查詢記錄
select * from user

結果:
id   username  password
1    admin        123456
3    tom            123456

由此可見 id=2被刪除了

其中 有人疑惑,爲什麼sql語句不這樣寫
delete from user where id in(select max(id) from user group by username having count(*)>=2)

但這樣寫會報錯  You can't specify target table <tbl> for update in FROM clause
剛開始自己也很疑惑,後來借鑑了一下別人的資料才知道。
MySQL中 不能先select出同一表中的某些值,再update這個表(在同一語句中),也就是說你不能 對同一張表先selete 然後在 delete update  ,所以只能通過一張中間表來操作了, 其實這裏的中間表也是 自表查詢,只是取了個別名,數據庫就不認爲是同一張表了。







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章