To_DAYS函数
to_days(2022-8-25)表示返回0到2022年8月25日的天数,但是通常不这么使用,常见的例如使用to_days函数统计昨天或前天的数据,比如:
统计昨天的所有数据
select *
from 表名
where to_days(now())-to_days(created_time) = 1;
统计前天的所有数据
select *
from 表名
where to_days(now())-to_days(created_time) = 2;
DATEDIFF函数
在MYSQL中,可以使用DATEDIFF()函数返回两个日期之间的天数。它适用于任何可以解析为time、date或datetime值的表达式。因此,可以得到两次的差值。
DATEDIFF()函数语法如下:
DATEDIFF (startdate , enddate )
其中startdate是第一个日期,enddate是结束日期。
它的工作方式是从enddate中减去startdate。例如:
查询当天的所有数据
select *
from 表名
where datediff(字段,now())=0
查询昨天的所有数据
select *
from 表名
where datediff(字段,now())=-1
注意:因为对索引列使用函数会导致索引失效,如果查询时需要使用到索引,请使用MySQL DATE_SUB()
函数
这里引用一下leetcode上的一道sql题(197.上升的温度),如下
很简单的一条sql,我们就拿这个来解释一下Mysql中的TO_DAYS函数和DATE_DIFF函数。
对比一下这两种函数的使用
//ANSWER1(使用to_days函数)
select w1.id
from Weather w1,Weather w2
where to_days(w1.RecordDate) - to_days(w2.RecordDate) = 1
and w1.temperature > w2.temperature;
//ANSWER2(使用DATEDIFF函数)
select w1.id
from Weather w1,Weather w2
where datediff(w1.RecordDate,w2.RecordDate) = 1
and w1.Temperature > w2.Temperature
以上两种sql返回结果均正确