MySQL: select last full 5 minute interval

2019-07-13 01:07发布

I want to select from my table the last full 5 minute interval.

Example:

  • Time now: 09:32 am --> select --> 09:25 - 09:30 am
  • Time now: 10:44 pm --> select --> 10:35 - 10:40 pm

enter image description here

I know how to group my select into 5 minute intervals

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,

I also know how to select the last 5 minutes

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

But how do I get the last full 5 minute interval like shown in the example above?

5条回答
仙女界的扛把子
2楼-- · 2019-07-13 01:52

You were close:

WHERE endtime > date_sub(now(), interval 3 minute);
查看更多
Lonely孤独者°
3楼-- · 2019-07-13 01:59

use

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

You will get x (1-12), after that just multiply it by 5

if we are are "32" then x = 7 (32/5 = 6.x => 7)

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

=== added ====

just concat it into an hour

查看更多
聊天终结者
4楼-- · 2019-07-13 01:59

I think I got it:

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

Result

enter image description here

查看更多
甜甜的少女心
5楼-- · 2019-07-13 02:00

If you just want to limit the result set to records happening within 5 minutes of the most recent endtime then you can try the following:

SELECT *
FROM yourTable
WHERE endtime > (SELECT MAX(endtime) FROM yourTable) - INTERVAL 5 MINUTE
查看更多
够拽才男人
6楼-- · 2019-07-13 02:01

Your question is still not very clear as you didn't mention expected output based on your input. However, you can use this code to get start_time and end_time based on now(). Change now() as per your requirement.

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

Explanation: First divide the minutes by 5, then take the floor(remove decimal) and multiply it by 5. This will give you nearest end time. Subtract 5 minutes from it to get start_time.

查看更多
登录 后发表回答