Remove duplicate rows in MySQL

前端 未结 25 3459
囚心锁ツ
囚心锁ツ 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:33

    MySQL has restrictions about referring to the table you are deleting from. You can work around that with a temporary table, like:

    create temporary table tmpTable (id int);
    
    insert  into tmpTable
            (id)
    select  id
    from    YourTable yt
    where   exists
            (
            select  *
            from    YourTabe yt2
            where   yt2.title = yt.title
                    and yt2.company = yt.company
                    and yt2.site_id = yt.site_id
                    and yt2.id > yt.id
            );
    
    delete  
    from    YourTable
    where   ID in (select id from tmpTable);
    

    From Kostanos' suggestion in the comments:
    The only slow query above is DELETE, for cases where you have a very large database. This query could be faster:

    DELETE FROM YourTable USING YourTable, tmpTable WHERE YourTable.id=tmpTable.id
    

提交回复
热议问题