【问题标题】:How to get rows between two hours from a datetime column?如何从日期时间列中获取两个小时之间的行?
【发布时间】:2019-10-15 19:15:34
【问题描述】:

我有一个datetime 专栏。如何获取 Date 列在两个特定小时之间的行(不考虑日、月和年)。

例如,小时在14:00:0015:00:00 之间的任何行(全天)?

【问题讨论】:

    标签: mysql sql datetime


    【解决方案1】:

    您可以使用time()hour()

    where hour(datetime) >= 14 and hour(datetime) < 16
    

    或:

    where time(datetime) >= '14:00:00' and time(datetime) < '16:00:00'
    

    或者你可能更喜欢这样:

    where time(datetime) >= '14:00:00' and
          time(datetime) < '15:00:00' + interval 1 hour
    

    注意:由于datetime 列上的函数调用,这些都不会使用索引。

    【讨论】:

      【解决方案2】:

      试试这个

      select * from table where hour(datetime) between 14 and 16
      

      select * from table where time(datetime) between '14:00:00' and '16:00:00'

      【讨论】:

        【解决方案3】:
        select *
         from (
          select cast (substr(to_char(datetime,'YYYY-mm-dd HH:MM:SS'),12,2) as integer ) as compare 
              from table )
        where compare between 14 and 15;
        

        【讨论】:

        • 请在您的代码中添加一些解释,以便其他人可以从中学习
        • 1)to_char(datetime,'YYYY-mm-dd HH:MM:SS') => 这会将您的日期转换为字符串 2)substr(to_char(datetime,'YYYY-mm-dd HH :MM:SS'),12,2) => 这个 substr 函数选择指定的字符串,即该字符串的开始和结束部分。 3)cast (substr(to_char(datetime,'YYYY-mm-dd HH:MM:SS'),12,2) as integer ) => 然后将所选字符串转换为整数然后你可以比较这个整数。跨度>
        • 请将所有解释添加到答案中,而不是添加到评论部分
        猜你喜欢
        • 1970-01-01
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 2012-03-24
        • 1970-01-01
        • 2020-07-24
        相关资源
        最近更新 更多