使用 MySQL 获取 CURDATE() 和前一天的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13572083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:34:06  来源:igfitidea点击:

Grab where CURDATE() and the day before with MySQL

mysql

提问by Karem

offers.date = CURDATE() 

I what I currently have.

我现在拥有的。

It grabs offers for today, but I also would like to grab the orders for yesterday.

它获取今天的报价,但我也想获取昨天的订单。

How can I do this, without specifying the yesterday's date?

我怎么能做到这一点,而不指定昨天的日期?

回答by edwardmp

To use CURDATE minus or plus a interval (e.g. yesterday) you can use the DATE_ADDfunction

要使用 CURDATE 减去或加上一个间隔(例如昨天),您可以使用DATE_ADD函数

SELECT DATE_ADD(CURDATE(), INTERVAL -1 DAY);

So, in your case you use it like this:

因此,在您的情况下,您可以这样使用它:

WHERE offers.date = CURDATE() OR offers.date = DATE_ADD(CURDATE(), INTERVAL -1 DAY)

Optionally you can also use the DATE_SUB() function and instead of a negative interval use the same interval but positive.

您也可以选择使用 DATE_SUB() 函数,而不是负间隔,使用相同但正的间隔。

Thus, DATE_ADD(CURDATE(), INTERVAL -1 DAY)would become DATE_SUB(CURDATE(), INTERVAL 1 DAY)

这样,DATE_ADD(CURDATE(), INTERVAL -1 DAY)就会变成DATE_SUB(CURDATE(), INTERVAL 1 DAY)

回答by Rick Thacker

Seems to me like it would be simpler to just say the following

在我看来,只说以下内容会更简单

WHERE offers.date >= CURDATE() - INTERVAL 1 day

回答by Ike Walker

Building on @edwardmp's answer, I find this syntax slightly more readable than using DATE_ADD():

基于@edwardmp 的回答,我发现这个语法比使用更易读DATE_ADD()

current_date() - interval 1 day

Also I would use INinstead of ORto make it easier to combine this with the rest of your where clause without having to worry too much about parentheses:

此外,我会使用IN而不是OR更容易地将它与您的 where 子句的其余部分结合起来,而不必太担心括号:

WHERE offers.date in (current_date(), current_date() - interval 1 day)

回答by saherr1969

It could also be

也可以

  offers.date between (current_date() - interval 1 day) and current_date

NB: that this will fail if offers.date is a datetime value because (2017-01-02) < (2017-01-02 12:34:56) due to the fact 2017-01-02 is actually 2017-01-02 00:00:00.

注意:如果 offer.date 是日期时间值,这将失败,因为 (2017-01-02) < (2017-01-02 12:34:56) 由于 2017-01-02 实际上是 2017-01- 02 00:00:00。