How to delete duplicates on a MySQL table?

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

    I find Werner's solution above to be the most convenient because it works regardless of the presence of a primary key, doesn't mess with tables, uses future-proof plain sql, is very understandable.

    As I stated in my comment, that solution hasn't been properly explained though. So this is mine, based on it.

    1) add a new boolean column

    alter table mytable add tokeep boolean;
    

    2) add a constraint on the duplicated columns AND the new column

    alter table mytable add constraint preventdupe unique (mycol1, mycol2, tokeep);
    

    3) set the boolean column to true. This will succeed only on one of the duplicated rows because of the new constraint

    update ignore mytable set tokeep = true;
    

    4) delete rows that have not been marked as tokeep

    delete from mytable where tokeep is null;
    

    5) drop the added column

    alter table mytable drop tokeep;
    

    I suggest that you keep the constraint you added, so that new duplicates are prevented in the future.

提交回复
热议问题