如何在MySQL的现在和午夜之间写出时间查询?

时间:2012-12-06 07:25:49

标签: mysql

我的查询如下

SELECT * FROM programs where startTime between now() and now() + INTERVAL 1 DAY;

是否有可能在MySQL的现在和午夜之间编写查询?

如下所示

SELECT * FROM programs where startTime between now() and now() + midnight 12;

5 个答案:

答案 0 :(得分:11)

我建议您始终使用clopen(闭合开放)间隔进行日期和时间比较。 BETWEEN表示封闭间隔(从两侧)。 @Aaron Bertrand's博文中有一个非常好的解释: What do BETWEEN and the devil have in common? 。这是编写查询的方法:

SELECT * 
FROM programs 
WHERE startTime >= NOW() 
  AND startTime < CURRENT_DATE() + INTERVAL 1 DAY ;

答案 1 :(得分:5)

SELECT * FROM programs where startTime between now() and CURRENT_DATE() + INTERVAL 1 DAY;

当前日期返回当天的开头,然后我们添加1天以结束它。

答案 2 :(得分:0)

试试这个::

SELECT * FROM programs where startTime between now() and DATE_SUB(CURDATE(), INTERVAL 1 DAY)

答案 3 :(得分:0)

您可以尝试以下方法:可能会很长。

样本表:

ID  STIME                               ETIME
1   December, 05 2012 05:23:00+0000     December, 05 2012 07:30:00+0000
2   December, 05 2012 10:23:00+0000     December, 05 2012 12:30:00+0000
3   December, 06 2012 22:45:00+0000     December, 07 2012 01:00:00+0000
4   December, 06 2012 22:23:00+0000     December, 06 2012 23:55:00+0000
5   December, 06 2012 20:23:00+0000     December, 06 2012 22:55:00+0000
6   December, 07 2012 10:23:00+0000     December, 07 2012 12:30:00+0000

<强>查询

SELECT  *,curtime() FROM prog
WHERE date(stime) = date(now())
AND date(etime) = date(now())
AND time_to_sec(SUBTIME(etime,'24:00:00')) >= 0
;

<强>结果

ID  STIME                               ETIME   
4   December, 06 2012 22:23:00+0000     December, 06 2012 23:55:00+0000     
5   December, 06 2012 20:23:00+0000     December, 06 2012 22:55:00+0000     

答案 4 :(得分:0)

SELECT *
FROM   programs
WHERE  DATE(startTime) = CURRENT_DATE AND startTime > CURRENT_TIMESTAMP