示例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
答案 0 :(得分:2)
我会根据相关的子查询检查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
修改强>
同一逻辑的另一个重构
答案 1 :(得分:-1)
确保UpdateDate是DATETIME字段。
您是否希望为每个答案值保留最新的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 );
答案 2 :(得分:-1)
您可以使用临时变量来存储最高日期,然后使用单独的查询来删除所有&lt;比起那个来说。请记住,变量是特定于连接的。
select max(UpdateDate) from table_1 into @TempUpdateDate
delete from table_1 where UpdateDate < @TempUpdateDate