MySQL delete duplicate records but keep latest

后端 未结 7 1421

I have unique id and email fields. Emails get duplicated. I only want to keep one Email address of all the duplicates but with the latest id<

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 23:10

    I personally had trouble with the top two voted answers. It's not the cleanest solution but you can utilize temporary tables to avoid all the issues MySQL has with deleting via joining on the same table.

    CREATE TEMPORARY TABLE deleteRows;
    SELECT MIN(id) as id FROM myTable GROUP BY myTable.email;
    
    DELETE FROM myTable
    WHERE id NOT IN (SELECT id FROM deleteRows);
    

提交回复
热议问题