且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在查询中的MYSQL日期中增加天数

更新时间:2023-01-29 23:31:10

您似乎想要的行end_date早于五天前.

It looks like you want rows where end_date is later than five days ago.

***的方法是

 WHERE end_date >= CURDATE() - INTERVAL 5 DAY

将整数添加到日期的业务在MySQL中不起作用(这是Oracle的事情).因此,您需要使用INTERVAL n unit语法.

The business of adding integers to dates doesn't work in MySQL (it's an Oracle thing). So you need to use the INTERVAL n unit syntax.

您会注意到,我上面的WHERE子句在功能上等同于

You'll notice that my WHERE clause above is functionally equivalent to

 WHERE DATE(end_date) + INTERVAL 5 DAY >= DATE(NOW())

但是,由于两个原因,第一种方法要优于第二种方法.

But, the first formulation is superior to the second for two reasons.

  1. 如果您在WHERE子句中提及end_date而不将其包装在计算中,则您的查询可以利用该列上的索引,并且可以更快地运行.
  2. DATE(NOW())CURDATE()均指今天的第一时刻(午夜).但是CURDATE()有点简单.
  1. if you mention end_date in a WHERE clause without wrapping it in computations, your query can exploit an index on that column and can run faster.
  2. DATE(NOW()) and CURDATE() both refer to the first moment of today (midnight). But CURDATE() is a bit simpler.