How to delete duplicates on a MySQL table?

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

    Another easy way... using UPDATE IGNORE:

    U have to use an index on one or more columns (type index). Create a new temporary reference column (not part of the index). In this column, you mark the uniques in by updating it with ignore clause. Step by step:

    Add a temporary reference column to mark the uniques:

    ALTER TABLE `yourtable` ADD `unique` VARCHAR(3) NOT NULL AFTER `lastcolname`;
    

    => this will add a column to your table.

    Update the table, try to mark everything as unique, but ignore possible errors due to to duplicate key issue (records will be skipped):

    UPDATE IGNORE `yourtable` SET `unique` = 'Yes' WHERE 1;
    

    => you will find your duplicate records will not be marked as unique = 'Yes', in other words only one of each set of duplicate records will be marked as unique.

    Delete everything that's not unique:

    DELETE * FROM `yourtable` WHERE `unique` <> 'Yes';
    

    => This will remove all duplicate records.

    Drop the column...

    ALTER TABLE `yourtable` DROP `unique`;
    

提交回复
热议问题