每天在mysql中删除除max(timestamp)以外的所有行

时间:2018-07-26 12:10:46

标签: mysql sql

如何删除每天除每种货币的max(timestamp)以外的所有行。因此,查询必须每天仅保留每种货币的最新行。

数据

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))

5 个答案:

答案 0 :(得分:1)

时间戳最高的行似乎也具有最高的ID。

DELETE FROM YourTable
WHERE Id NOT IN (SELECT MAX(Id) FROM YourTable GROUP BY currency, DATE(timestamp))

答案 1 :(得分:0)

您可以使用行号完成操作。像这样:

WITH CTE AS
(
  SELECT Currency,
         Timestamp,
         ROW_NUMBER() OVER (PARTITION BY Currency ORDER BY TIMESTAMP DESC) AS RowNumb
  FROM Table
)  

DELETE FROM CTE WHERE RowNumb > 1

答案 2 :(得分:0)

返回不删除行的子查询将帮助您:

DELETE FROM table_test
WHERE Id <> (SELECT last.id 
             FROM table_test last
             WHERE cast(last.created_at as date) = cast(table_test.created_at as date)
             ORDER BY last.created_at DESC
             LIMIT 1)

答案 3 :(得分:0)

一种方法是选择每种货币和日期的最大时间戳,并将其从删除中排除:

delete from tbltest
where (currency, created_at) not in
(
  select currency, max(created_at)
  from (select * from tbltest) t
  group by currency, date(created_at)
);

我认为这是易读的,我认为这在编写SQL时很重要。

from (select * from tbltest) t

很奇怪。这是因为MySQL拒绝您直接查询同一表的更新。在其他DBMS中,您只需写from tbltest

如果您喜欢它,可以更改

where (currency, created_at) not in
(
  select currency, max(created_at)

where (currency, date(created_at), created_at) not in
(
  select currency, date(created_at), max(created_at)

当然也做同样的事情。选择您认为更具可读性/直观性的版本。

答案 4 :(得分:-1)

您可以使用以下sql语句

*  *    * * *   ubuntu    wget https://google.com

让我知道它是否有效! :)