curdate() 在 MySQL 中如何进行比较

发布于 2024-10-14 22:01:20 字数 485 浏览 8 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紙鸢 2024-10-21 22:01:20

如果您的 created_at 列是完整的 datetime 类型,那么在与日期进行比较时,它将采用该日期的开始时间。

因此,与 2011-01-01 进行比较类似于与 2011-01-01 00:00:00 进行比较。这就是为什么您无法从 CURDATE() 获取任何信息(除非 created_at 时间戳恰好是该日期的午夜)。

例子:

select curdate();
-- 2011-01-31

select cast(curdate() as datetime);
-- 2011-01-31 00:00:00

select if('2011-01-31' <= curdate(), 'yep', 'not this time');
-- yep

select if('2011-01-31 00:00:01' <= curdate(), 'yep', 'not this time');
-- not this time

select if('2011-01-31 01:00:00' <= adddate(curdate(), interval 1 day), 'yep', 'not this time');
-- yep

If your created_at column is a full datetime 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 to 2011-01-01 00:00:00. That's why you're not getting anything back for CURDATE() (unless the created_at timestamp is exactly midnight on that date).

Example:

select curdate();
-- 2011-01-31

select cast(curdate() as datetime);
-- 2011-01-31 00:00:00

select if('2011-01-31' <= curdate(), 'yep', 'not this time');
-- yep

select if('2011-01-31 00:00:01' <= curdate(), 'yep', 'not this time');
-- not this time

select if('2011-01-31 01:00:00' <= adddate(curdate(), interval 1 day), 'yep', 'not this time');
-- yep
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文