How to delete duplicates on a MySQL table?

后端 未结 25 2408
遇见更好的自我
遇见更好的自我 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 02:02

    Following remove duplicates for all SID-s, not only single one.

    With temp table

    CREATE TABLE table_temp AS
    SELECT * FROM table GROUP BY title, SID;
    
    DROP TABLE table;
    RENAME TABLE table_temp TO table;
    

    Since temp_table is freshly created it has no indexes. You'll need to recreate them after removing duplicates. You can check what indexes you have in the table with SHOW INDEXES IN table

    Without temp table:

    DELETE FROM `table` WHERE id IN (
      SELECT all_duplicates.id FROM (
        SELECT id FROM `table` WHERE (`title`, `SID`) IN (
          SELECT `title`, `SID` FROM `table` GROUP BY `title`, `SID` having count(*) > 1
        )
      ) AS all_duplicates 
      LEFT JOIN (
        SELECT id FROM `table` GROUP BY `title`, `SID` having count(*) > 1
      ) AS grouped_duplicates 
      ON all_duplicates.id = grouped_duplicates.id 
      WHERE grouped_duplicates.id IS NULL
    )
    

提交回复
热议问题