How to delete duplicates on a MySQL table?

后端 未结 25 2987
遇见更好的自我
遇见更好的自我 2020-11-22 01:35

I need to DELETE duplicated rows for specified sid on a MySQL table.

How can I do this with an SQL query?

         


        
25条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 01:56

    This procedure will remove all duplicates (incl multiples) in a table, keeping the last duplicate. This is an extension of Retrieving last record in each group

    Hope this is useful to someone.

    DROP TABLE IF EXISTS UniqueIDs;
    CREATE Temporary table UniqueIDs (id Int(11));
    
    INSERT INTO UniqueIDs
        (SELECT T1.ID FROM Table T1 LEFT JOIN Table T2 ON
        (T1.Field1 = T2.Field1 AND T1.Field2 = T2.Field2 #Comparison Fields 
        AND T1.ID < T2.ID)
        WHERE T2.ID IS NULL);
    
    DELETE FROM Table WHERE id NOT IN (SELECT ID FROM UniqueIDs);
    

提交回复
热议问题