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“。