Remove duplicate rows in a table having no primary key

蓝咒 提交于 2019-12-05 00:26:49

问题


I have a table item that contains items like

name
------
alpha
alpha 
beta
charlie
charlie

In this case how would I delete duplicate rows but one record should remain. The above table does not have any primary key.


回答1:


Try this

DELETE FROM item WHERE GREATEST(0,@num := IF(NAME = @NAME, @num + 1, 0),LEAST(0, LENGTH(@NAME := NAME)))>0



回答2:


Recreate that table:

RENAME TABLE `testTable` TO `testTable2`;

CREATE TABLE `testTable` 
SELECT DISTINCT `name` FROM `testTable2`;

OR Add UNIQUE INDEX on your field.

ALTER IGNORE TABLE `tableName` 
    ADD UNIQUE INDEX (`name`)


来源:https://stackoverflow.com/questions/14357888/remove-duplicate-rows-in-a-table-having-no-primary-key

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