两个日期之间的mysql选择有奇怪的行为

时间:2018-05-30 02:00:54

标签: mysql sql datetime between

我正在选择NOW()和特定X天间隔之间的所有记录,并遇到了我不理解的奇怪行为。

我正在检查未来24小时和过去24小时:

select * from table where date between NOW() and NOW() + 1 interval day; //works
select * from table where date between NOW() and NOW() - 1 interval day; //no records

但如果我撤消between来电:

select * from table where date between NOW() + 1 interval day AND NOW(); //no records
select * from table where date between NOW() - 1 interval day AND NOW(); //works

为什么一个人打电话给未来的工作,但同样的调用过去不起作用?...如果我反转between参数,相反的行为发生 - 在未来24小时不起作用但在过去24小时工作。

======================

在下面添加@TimBiegeleisen说明:

date = '2018-05-30' ;

select * from table where date between NOW() and NOW() + 1 interval day;
     = date >= '2018-05-30' AND 'date <= 2018-05-31'; //true
select * from table where date between NOW() and NOW() - 1 interval day; records
     = date >= '2018-05-30' AND 'date <= 2018-05-29'; //false

select * from table where date between NOW() + 1 interval day AND NOW();
     = date >= '2018-05-31' AND date <= '2018-05-30' //false
select * from table where date between NOW() - 1 interval day AND NOW();
     = date >= '2018-05-29' and date <= '2018-05-30'; //true

2 个答案:

答案 0 :(得分:3)

BETWEEN运算符以某种方式解释:

WHERE date BETWEEN a AND b

意味着:

WHERE date >= a AND date <= b

所以以下两个查询是等价的:

select * from table where date between NOW() and NOW() - interval 1 day;
select * from table where date >= NOW() and date <= NOW() - interval 1 day;

希望您可以在第二个查询中看到WHERE条件永远不会成立,因为日期不能同时大于或等于现在小于现在减去1同时。

答案 1 :(得分:0)

简单地说,

对于SQL: WHERE x between a and b

x >= ax <= b

因此,我们有a <= x <= ba <= b

PS:这只是数学:)