【问题标题】:Select between date range and specific time range在日期范围和特定时间范围之间进行选择
【发布时间】:2013-12-06 14:07:18
【问题描述】:

有没有办法在日期和特定时间范围之间选择记录。例如从 2013-11-01 到 2013-11-30 在 05:00 到 15:00 之间的所有记录。这是我到现在为止所做的。

    select count(*) as total from tradingaccounts accounts
inner join tradingaccounts_audit audit on audit.parent_id = accounts.id
where date(audit.date_created) between date('2013-11-01 00:00:00') AND date('2013-11-01 23:59:59') 

但是具体的时间范围我要怎么设置呢?

【问题讨论】:

    标签: mysql sql select time


    【解决方案1】:

    您可以使用HOUR 函数在小时数上添加附加条件:

    select count(*) as total from tradingaccounts accounts
    inner join tradingaccounts_audit audit on audit.parent_id = accounts.id
    where date(audit.date_created) between date('2013-11-01 00:00:00') AND date('2013-11-01 23:59:59') 
    AND HOUR (audit.date_created) BETWEEN 5 AND 15
    

    【讨论】:

    • 有没有办法说 hours:mins:secs 之间而不是 hour ?
    • @user1292656 当然 - 您可以使用 TIME 函数。例如,TIME(audit.date_created) BETWEEN '05:00:00' AND '15:00:00'.
    【解决方案2】:

    替换您的 DATE 函数,它会跳过时间部分。请改用TIMESTAMP

    【讨论】:

      【解决方案3】:

      在查询中添加以下行并在 BETWEEN 中设置您的小时

      和时间(audit.date_created)在'00:00:01'和'01:00:00'之间

      【讨论】:

        【解决方案4】:

        正如其他人回答的那样,HOUR() 可以帮助您。

        但是 HOUR() 或 DATE() 不能使用 INDEX。为了使查询更快,我建议添加 time_created TIME 列并仅保存 TIME 部分。之后ADD INDEX(date_created, time_created)。最后通过以下查询,您可以高速检索行。

        where audit.date_created between '2013-11-01 00:00:00' AND '2013-11-01 23:59:59'
          AND audit.time_created BETWEEN '05:00:00' AND '15:00:00'
        

        【讨论】:

          【解决方案5】:

          如果使用date(audit.date_created)date_created字段上的索引无法生效。

          只需使用where audit.date_created >= 'xx-xx-xx' and audit.date_created < 'xx-xx-xx'

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-12-14
            • 1970-01-01
            • 2013-03-27
            • 1970-01-01
            • 2017-12-30
            • 2012-04-12
            • 1970-01-01
            相关资源
            最近更新 更多