How to delete duplicates on a MySQL table?

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

    After running into this issue myself, on a huge database, I wasn't completely impressed with the performance of any of the other answers. I want to keep only the latest duplicate row, and delete the rest.

    In a one-query statement, without a temp table, this worked best for me,

    DELETE e.*
    FROM employee e
    WHERE id IN
     (SELECT id
       FROM (SELECT MIN(id) as id
              FROM employee e2
              GROUP BY first_name, last_name
              HAVING COUNT(*) > 1) x);
    

    The only caveat is that I have to run the query multiple times, but even with that, I found it worked better for me than the other options.

提交回复
热议问题