MySQL date_add() 在 WHERE 子句中不起作用?
当我尝试运行以下查询时:
... WHERE `date` = DATE_ADD(NOW(), INTERVAL 10 HOUR)
它不起作用,因此我必须使用 $date = date("Ymd", strtotime('+10 hours'))
但为什么 date_add
不起作用?
非常感谢
When I try to run the following query:
... WHERE `date` = DATE_ADD(NOW(), INTERVAL 10 HOUR)
It doesn't work, so I have to use the $date = date("Y-m-d", strtotime('+10 hours'))
But why date_add
doesn't work?
Thanks much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请注意
DATE_ADD( )
函数除了日期之外还返回时间部分。这与使用 php 的date("Ymd", strtotime('+10 hours'))
不同,后者仅返回日期部分。您可以使用
WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
代替:测试用例:
Note that
DATE_ADD()
function returns a time part in addition to the date. This is not the same as using php'sdate("Y-m-d", strtotime('+10 hours'))
, which only returns the date part.You could use
WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
instead:Test case:
NOW()
是时间戳,而不是日期。示例:
我认为这就是您想要的:
NOW()
is a timestamp, not a date.Example:
I think this is what you want:
您将 DateTime(
DATE_ADD
的结果)与 DATE 进行比较。您需要WHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
You compare DateTime (result of
DATE_ADD
) with DATE. You needWHERE date = DATE(DATE_ADD(NOW(), INTERVAL 10 HOUR))
这:
...确实有效(假设
date
是DATETIME),但它包括执行语句时的时间部分——
date`值需要与< em>完全要返回。This:
...does work (assuming
date
is DATETIME), but it includes the time portion when the statement was executed -- the
date` values need to match that exactly to be returned.我知道这个问题已经得到解答,但在这个用例中有一个更好的解决方案:
DATE_ADD(TODAY(), INTERVAL 10 HOUR)
这会删除一个额外的操作,因为
TODAY
返回日期而没有时间部分。I know this is answered already but there is a better solution in this usecase:
DATE_ADD(TODAY(), INTERVAL 10 HOUR)
This removes one additional operation because
TODAY
returns date without time part.