开发者

How curdate() works in comparisons in 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 be开发者_JS百科cause 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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜