Mysql Datediff 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7712677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql Datediff query
提问by sathish
I need to get the result from the table, which the date should be difference of 5 from the current date.
我需要从表中获取结果,该日期应与当前日期相差 5。
ie., specific_date
column is present in my table. The format of the date is YYYY-MM-DD
.
即,specific_date
列存在于我的表中。日期的格式是YYYY-MM-DD
.
I need the query something like,
我需要这样的查询,
SELECT * FROM `table_name` WHERE DATEDIFF(NOW(), specific_date) < 5
回答by O. Jones
It looks like you are trying to do this:
看起来您正在尝试执行此操作:
WHERE specific_date < (NOW() + 5 days)
First of all, think carefully about the boundary cases. These boundary cases can bite your ankles in SQL. Do you actually want
首先,仔细考虑边界情况。这些边界情况可能会在 SQL 中咬你的脚踝。你真的想要吗
WHERE specific_date <= (NOW() + 5 days)
Do your specific_date
columns timestamps contain only days (that is dates with times equal to midnight) or do they contain dates and times? If you're going to get the results you want, you need to be careful about those details.
您的specific_date
时间戳列仅包含天数(即时间等于午夜的日期)还是包含日期和时间?如果您要获得想要的结果,则需要注意这些细节。
At any rate, try this:
无论如何,试试这个:
WHERE specific_date <= DATE_ADD(NOW(), INTERVAL 5 DAY)
This is a good way to do such a lookup. The column value stands alone on one side of the inequality predicate (the <=
) so mySQL can do an index range scan if you have an index on the column.
这是进行此类查找的好方法。列值独立于不等式谓词 (the <=
) 的一侧,因此如果列上有索引,mySQL 可以执行索引范围扫描。
Date arithmetic in MySQL is quite flexible. You can do
MySQL 中的日期算法非常灵活。你可以做
NOW() + INTERVAL 10 SECOND
NOW() - INTERVAL 2 MINUTE
NOW() + INTERVAL 4 HOUR
CURDATE() - INTERVAL 1 WEEK /* midnight one week ago */
LAST_DAY(NOW()) + INTERVAL 1 DAY - INTERVAL 1 MONTH /*first day of present month*/
NOW() - INTERVAL 1 QUARTER
CURDATE() - INTERVAL 5 YEAR
and so forth.
等等。