【发布时间】:2019-01-03 10:24:03
【问题描述】:
如何删除每天除每种货币的最大(时间戳)之外的所有行。因此,查询必须每天只保留每种货币的最新行。
数据
Id,currency,value,timestamp
21,btc,8000,2018-07-25 23:00:00 --> Keep this row
20,eth, 800,2018-07-25 23:00:00 --> Keep this row
19,btc,7999,2018-07-25 22:00:00
18,eth, 799,2018-07-25 22:00:00
17,btc,7998,2018-07-25 21:00:00
16,eth, 798,2018-07-25 21:00:00
15,btc,7997,2018-07-24 23:00:00 --> Keep this row
14,eth, 800,2018-07-24 23:00:00 --> Keep this row
13,btc,7996,2018-07-24 22:00:00
12,eth, 799,2018-07-24 22:00:00
11,btc,7995,2018-07-24 21:00:00
10,eth, 798,2018-07-24 21:00:00
每种货币每天的最新 (max(created_at)) 行
SELECT
t.currency
, DATE(t.created_at)
, MAX(t.created_at)
FROM `tbltest` t
GROUP BY
t.currency
, DATE(t.created_at)
我可以找到每种货币每天最新的 (max(created_at)) 行,但我如何只保留这些行,而删除所有其他行?
解决方案
由于最高的时间戳也有最高的 id,所以使用的简单解决方案如下:
DELETE FROM `tbltest`
WHERE id NOT IN
(SELECT MAX(id)
FROM (select * FROM `tbltest`) as t2
GROUP BY currency, DATE(created_at))
【问题讨论】:
-
DELETE DROM tablename WHERE NOT IN([your max query])