How to remove mySQL duplicate entries

孤街醉人 提交于 2019-12-11 03:58:28

问题


I have a mySQL table with duplicate entries (perhaps in some cases multiple duplicates). I have column called id, which may contain duplicate ids and one called unique id which, as the name suggest contains unique ids. Using the following SQL statement I am able to select the duplicate row

SELECT id,
COUNT(id) AS NumOccurrences
FROM `TABLE 3`
GROUP BY id
HAVING ( COUNT(id) > 1 )

but how do I delete (all but one of) them?


回答1:


DELETE t1 FROM test t1, test t2 WHERE t1.unique_id > t2.unique_id AND t1.id = t2.id;



回答2:


You should add a UNIQUE INDEX on the unique id field. This will prevent more duplicates from sneaking in later.

ALTER IGNORE `TABLE 3` ADD UNIQUE INDEX (`unique_id`);

The IGNORE bit will only keep the first row with the value "unique_id". You should also avoid using spaces in your column or table names. It makes writing SQL error prone as you have to use ticks around names.



来源:https://stackoverflow.com/questions/11621314/how-to-remove-mysql-duplicate-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!