MySQL: select 最后完整的 5 分钟间隔

MySQL: select last full 5 minute interval

我想 select 从我的 table 最后一个完整的 5 分钟间隔开始。

示例:

我知道如何将 select 分组为 5 分钟的间隔

date_sub(date_sub(starttime, INTERVAL (MINUTE(starttime) % 5) MINUTE), INTERVAL (SECOND(starttime)) SECOND) as INTERVAL_START,
   date_add(date_sub(date_sub(starttime, INTERVAL (MINUTE(starttime) % 5) MINUTE), INTERVAL (SECOND(starttime)) SECOND), INTERVAL 5 MINUTE) as INTERVAL_END,

我也知道如何select最后5分钟

where  (endtime between now()-Interval 5 minute and now())

但是如何获得上例所示的最后一个完整的 5 分钟间隔?

如果您只想将结果集限制为最近 endtime 5 分钟内发生的记录,那么您可以尝试以下操作:

SELECT *
FROM yourTable
WHERE endtime > (SELECT MAX(endtime) FROM yourTable) - INTERVAL 5 MINUTE

你很接近:

WHERE endtime > date_sub(now(), interval 3 minute);

使用

select ceil(minute(now())/5) as `x`

你会得到 x (1-12),然后乘以 5

如果我们是“32”那么 x = 7 (32/5 = 6.x => 7)

between ((x-1)*5) and (x*5)    = (7-1)*5 and 7*5 = 30-35

=== 添加了 ====

把它拼成一个小时

你的问题还不是很清楚,因为你没有提到基于你的输入的预期输出。但是,您可以使用此代码根据 now() 获取 start_time 和 end_time。根据您的要求更改 now()

select 
date_sub(str_to_date(concat(hour(now()),':',floor(minute(now())/5)*5),'%H:%i'),interval 5 minute) as start_time,
str_to_date(concat(hour(now()),':',floor(minute(now())/5)*5),'%H:%i') as end_time,
now();

解释:首先将分钟数除以 5,然后取底数(去掉小数点)再乘以 5。这将得到最接近的结束时间。从中减去 5 分钟得到 start_time。

我想我明白了:

select  
   a.end_time - Interval 5 minute as start_time,
   a.end_time
from
   (
    select 
      str_to_date(concat(date(now()), ' ', hour(now()),':',floor(minute(now())/5)*5),'%Y-%m-%d %H:%i') as end_time
  ) a

结果