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

uqxowvwt  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(388)

我正在选择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
w7t8yxp5

w7t8yxp51#

这个 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 条件永远不可能是真的,因为一个日期不能同时大于或等于现在和小于现在减去一。

3mpgtkmj

3mpgtkmj2#

简单地说,
对于sql: WHERE x between a and b 意思 x >= a 以及 x <= b 因此,我们必须 a <= x <= b 或者 a <= b 附言:只是关于数学:)

相关问题