Remove duplicate rows in MySQL

前端 未结 25 3470
囚心锁ツ
囚心锁ツ 2020-11-21 04:33

I have a table with the following fields:

id (Unique)
url (Unique)
title
company
site_id

Now, I need to remove rows having same titl

25条回答
  •  无人共我
    2020-11-21 05:26

    A solution that is simple to understand and works with no primary key:

    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.

提交回复
热议问题