【问题标题】:MySQL: select last full 5 minute intervalMySQL:选择最后一个完整的 5 分钟间隔
【发布时间】:2017-08-05 21:27:24
【问题描述】:

我想从我的表格中选择最后一个完整的 5 分钟间隔。

例子:

  • 现在时间:09:32 am --> 选择 --> 09:25 - 09:30 am
  • 现在时间:晚上 10:44 --> 选择 --> 晚上 10:35 - 10:40

我知道如何将我的选择分组为 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,

我也知道怎么选择最后5分钟

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

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

【问题讨论】:

  • 你能给我们一些示例数据吗?

标签: mysql datetime intervals


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你很亲密:

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

    【讨论】:

    • 这可能适用于显示的数据,但如果当前时间发生变化,它将不起作用。
    【解决方案3】:

    使用

    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
    

    === 添加 ====

    只需将它连接到一个小时

    【讨论】:

      【解决方案4】:

      您的问题仍然不是很清楚,因为您没有根据您的输入提及预期的输出。但是,您可以使用此代码根据 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。

      【讨论】:

        【解决方案5】:

        我想我明白了:

        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
        

        结果

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-15
          • 1970-01-01
          • 2019-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-17
          • 1970-01-01
          相关资源
          最近更新 更多