[英]How do I delete records in MySQL and keep the lastest date
示例table_1
ID Email Answer UpdateDate
1 xxx.@xx.com 1 2011-07-02
2 xxx.@xx.com 3 2011-07-11
3 vvv.@xx.com 3 2011-07-12
4 vvv.@xx.com 5 2011-07-13
5 xxx.@xx.com 5 2011-07-14
6 xxx.@xx.com 4 2011-07-14
7 xxx.@xx.com 4 2011-07-14
8 zzz.@xx.com 4 2011-07-15
如何刪除此記錄但保留最新的UpdateDate
結果:
ID Email Answer UpdateDate
4 vvv.@xx.com 5 2011-07-13
7 xxx.@xx.com 4 2011-07-14
8 zzz.@xx.com 4 2011-07-15
我會根據相關的子查詢檢查 UpdateDate 。
CREATE TEMPORARY TABLE
latestRecord (
Email VARCHAR(128),
updateDate DATETIME
)
INSERT INTO
latestRecord
SELECT
Email,
MAX(updateDate) AS updateDate
FROM
table_1
GROUP BY
Emal
DELETE
table_1
FROM
table_1
INNER JOIN
latestRecord
ON latestRecord.Email = table_1.Email
AND latestRecord.updateDate < table_1.updateDate
編輯
相同邏輯的另一個重構
確保 UpdateDate 是 DATETIME 字段。
您想為每個 Answer 值保留最新的 UpdateDate 嗎? 這將做到這一點:
delete from table_1 where UpdateDate not in ( select max(UpdateDate) from table_1 group by Answer );
如果您只想保留最新日期,則:
delete from table_1 where UpdateDate not in ( select max(UpdateDate) from table_1 );
您可以使用臨時變量來存儲最高日期,然后使用單獨的查詢來刪除 < 的所有內容。 請記住,變量是特定於連接的。
select max(UpdateDate) from table_1 into @TempUpdateDate
delete from table_1 where UpdateDate < @TempUpdateDate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.