MySQL:比较BETWEEN时间

时间:2011-01-17 15:33:25

标签: mysql

这可能是不可能的,因为我想让它发挥作用,但现在就去了。

SELECT * FROM `table` WHERE CAST('05:00:00' AS time) BETWEEN `start` AND `end`

数据库中的条目是:

`start` = '22:59:59'
`end` = '06:00:00'

但是,查询不返回任何结果。当然,如果涉及日期,这将有效,但是没有。如果开始时间= '00:00:00',它也会起作用。

4 个答案:

答案 0 :(得分:20)

我认为你在寻找的是:

SELECT * FROM table WHERE start < CAST('05:00:00' AS time) AND end > CAST('05:00:00' AS time)

我不确定您是否需要使用CAST,但这也应该有效。

SELECT * FROM table WHERE start < '05:00:00' AND end > '05:00:00'

答案 1 :(得分:14)

SELECT  *
FROM    `table`
WHERE   CAST('05:00:00' AS time) BETWEEN `start` AND `end`
        OR (NOT CAST('05:00:00' AS time) BETWEEN `end` AND `start` AND `start` > `end`)

答案 2 :(得分:4)

我刚遇到这个问题,我遇到了同样的问题。我的解决方案如下:

SET @time = '05:00:00';

SELECT * FROM `table`
WHERE IF(
        `start` < `end`,
        CAST(@time AS TIME) BETWEEN `start` AND `end`,
        (CAST(@time AS TIME) BETWEEN CAST('00:00:00' AS TIME) AND `end`) OR 
        (CAST(@time AS TIME) BETWEEN `start` AND CAST('24:00:00' AS TIME))
    ) = 1;

希望将来帮助某人。

感谢Martin的提示!

答案 3 :(得分:2)

我们可以使用简单的时间到秒功能来比较时间。使用以下内容:

SELECT id
FROM table1
WHERE TIME_TO_SEC('2014-03-05 04:17:47') >= TIME_TO_SEC('2014-03-05 04:17:47');