MySQL:刪除重複記錄,同時保留最新的
問題:如何消除重複的電子郵件地址一個MySQL 表,同時根據唯一ID 欄位保留最新的表?
解決方案:
要實現此目的,請按照以下步驟操作:
識別重複電子郵件:
使用查詢來擷取所有重複電子郵件地址的清單:
SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1;
尋找每個重複郵件的最新ID:
SELECT MAX(id) AS lastID, email FROM test WHERE email IN ( SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1 ) GROUP BY email;
刪除最舊的重複項:
DELETE test FROM test INNER JOIN ( SELECT MAX(id) AS lastID, email FROM test WHERE email IN ( SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1 ) GROUP BY email ) duplic ON duplic.email = test.email WHERE test.id < duplic.lastID;
最佳化版本:
以下最佳化版本提供相同的結果,同時可能提高效能:DELETE test FROM test INNER JOIN ( SELECT MAX(id) AS lastID, email FROM test GROUP BY email HAVING COUNT(*) > 1) duplic ON duplic.email = test.email WHERE test.id < duplic.lastID;此修訂後的DELETE 語句著重於消除最舊的重複項。
附加選項:
或者,您可以利用Rene Limon 提供的此查詢:DELETE FROM test WHERE id NOT IN ( SELECT MAX(id) FROM test GROUP BY email);此方法根據最大ID 保留最新的重複電子郵件地址。
以上是如何刪除 MySQL 中重複的電子郵件地址,同時保留最新記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!