MySQL delete duplicate records but keep latest

后端 未结 7 1422

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:06

    I must say that the optimized version is one sweet, elegant piece of code, and it works like a charm even when the comparison is performed on a DATETIME column. This is what I used in my script, where I was searching for the latest contract end date for each EmployeeID:

    DELETE CurrentContractData
      FROM CurrentContractData
      INNER JOIN (
        SELECT
          EmployeeID,
          PeriodofPerformanceStartDate,
          max(PeriodofPerformanceEndDate) as lastDate,
          ContractID
        FROM CurrentContractData
        GROUP BY EmployeeID
        HAVING COUNT(*) > 1) Duplicate on Duplicate.EmployeeID = CurrentContractData.EmployeeID
        WHERE CurrentContractData.PeriodofPerformanceEndDate < Duplicate.lastDate;
    

    Many thanks!

提交回复
热议问题