delete duplicate rows and need to keep one from all of them in mysql [duplicate]

半腔热情 提交于 2019-12-21 13:01:22

问题


I want to delete duplicate rows based on two columns but need to keep 1 row all of them.

Duplicate rows can be more than two rows like,

ID  NAME PHONE
--  ---- ----
1   NIL  1234 
2   NIL  1234 
3   NIL  1234 
4   MES  5989

I want to delete any of 2 rows from above 3 and keep 1 row.


回答1:


DELETE  a
FROM    tableA a
        LEFT JOIN
        (
            SELECT MIN(ID) ID, Name, Phone
            FROM    TableA
            GROUP   BY Name, Phone
        ) b ON  a.ID = b.ID AND
                a.NAme = b.Name AND
                a.Phone = b.Phone
WHERE   b.ID IS NULL
  • SQLFiddle Demo

After you have executed the delete statement, enforce a unique constraint on the column so you cannot insert duplicate records again,

ALTER TABLE TableA ADD CONSTRAINT tb_uq UNIQUE (Name, Phone)



回答2:


DELETE
FROM Table
WHERE Table.id NOT IN  (  
    SELECT MIN(idTable) idtable
    FROM idTable
    GROUP BY name, phone)


来源:https://stackoverflow.com/questions/15548655/delete-duplicate-rows-and-need-to-keep-one-from-all-of-them-in-mysql

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