Mysql Datediff查询 [英] Mysql Datediff query

查看:150
本文介绍了Mysql Datediff查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从表中获取结果,日期应该与当前日期的差值为5。



ie。, specific_date 列存在于我的表中。日期的格式是 YYYY-MM-DD



我需要查询,

  SELECT * FROM`table_name` WHERE DATEDIFF(NOW(),specific_date)< 5 


解决方案

看起来你正在尝试这样做:

  WHERE specific_date< (NOW()+ 5天)

首先,仔细思考边界案例。这些边界案例可以在SQL中咬你的脚踝。你真的想要

  WHERE specific_date< =(NOW()+ 5天)

您的 specific_date 列时间戳只包含几天(即等于午夜的日期)还是包含日期和时间?如果你要得到你想要的结果,你需要注意这些细节。



无论如何,尝试这样做:

  WHERE specific_date< = DATE_ADD(NOW(),INTERVAL 5 DAY)

这是一个很好的方法来进行这样的查找。列值独立于不等式谓词(< = )的一侧,因此如果列上有索引,mySQL可以进行索引范围扫描。 p>

I need to get the result from the table, which the date should be difference of 5 from the current date.

ie., specific_date column is present in my table. The format of the date is YYYY-MM-DD.

I need the query something like,

SELECT * FROM `table_name` WHERE DATEDIFF(NOW(), specific_date) < 5

解决方案

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

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.

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.

这篇关于Mysql Datediff查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆