MySQL如何刪除重復記錄

jopen 10年前發布 | 12K 次閱讀 MySQL 數據庫服務器

方法有很多,除了最簡便的,

alter ignore table 表名  add UNIQUE index(字段名);

然后再將索引drop掉,這個方法外。

更加中規中矩的方法也是有的。。

比如我在網上搜到的:

delete from people 
where peopleId  in (select  peopleId  from people  group  by  peopleId   having  count(peopleId) > 1)
and id not in (select min(id) from  people  group by peopleId  having count(peopleId )>1)

這個看起來好像很有道理,但是執行的時候就會報錯。。You can't specify target table 'people' for update in FROM clause。

原因就是上面的那一條SQL,刪除和查詢操作都是針對同一張表的。。MYSQL是不允許這樣做滴。

這樣就可以了

delete from people 
where peopleId  in (select  peopleId  from(select id,peopleId from people) as a  group  by  peopleId   having  count(peopleId) > 1)
and id not in (select min(id) from  (select id,peopleId from people) as b group by peopleId  having count(peopleId )>1)

簡單一點的可以這樣寫

delete from id  where Id not in (select min(Id) from(selectid,peopleId from people)as a GROUP by peopleId );

粗體部分就是把一張表轉換成了一個提取表(derived table),從而解決了問題,需要注意的是后面那個as 別名,不能省略,否則會報錯"Every derived TABLE must have its own alias“。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!