curdate() 在 MySQL 中如何进行比较
我正在尝试使用 curdate() 检索数据库中的条目,我认为有一些我不知道的底层逻辑。例如:
SELECT * FROM foo WHERE event='bar'
AND created_at >= SUBDATE(CURDATE(), 90)
AND created_at <= CURDATE()
此调用返回前 90 天的数据,但没有今天的任何条目。据我了解 curdate() 只是 YYYY-MM-DD 或 YYYYMMDD 并且完全忽略一天中的时间,我们将其保存为 curtime() 和 now()。我怀疑这里的某个地方包含了时间,因为当我在 Rails 中进行类似的调用并将日期作为 DateTime.beginning_of_day 传递时,它会起作用,而任何其他方式都不会包含今天的某个小时。
我检查了一些资料,包括 MySQL 参考手册,但没有找到任何真正的答案。查询中是否可能包含当前时间的某些元素,或者是否有其他事务在幕后进行?
I'm trying to retrieve entries in my DB using curdate() and I think there is some underlying logic that I'm unaware of. For instance:
SELECT * FROM foo WHERE event='bar'
AND created_at >= SUBDATE(CURDATE(), 90)
AND created_at <= CURDATE()
This call returns with the previous 90 days but it does not have any of the entries from today. As I understand it curdate() is only YYYY-MM-DD or YYYYMMDD and completely ignores the time of day, we save that for curtime() and now(). I suspect that time is being included somewhere in here because when I make a similar call in Rails and pass the date as a DateTime.beginning_of_day it works whereas any other way it will not include today up to a certain hour.
I've checked out a few sources, including the MySQL reference manual, and haven't come up with any real answers. Is it possible that some element of the current time is being included in the query or is there some other business going on behind closed doors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的
created_at
列是完整的datetime
类型,那么在与日期进行比较时,它将采用该日期的开始时间。因此,与
2011-01-01
进行比较类似于与2011-01-01 00:00:00
进行比较。这就是为什么您无法从CURDATE()
获取任何信息(除非created_at
时间戳恰好是该日期的午夜)。例子:
If your
created_at
column is a fulldatetime
type, then when comparing to a date, it will take the beginning of that date.So, comparing to
2011-01-01
is akin to comparing to2011-01-01 00:00:00
. That's why you're not getting anything back forCURDATE()
(unless thecreated_at
timestamp is exactly midnight on that date).Example: