最近做项目要从记录里找出 并按距离当前时间最近的来排序,这就要计算每个记录的时间与当前时间的差值。一开始用了
ABS( log_time - NOW() )
但是发现出来的结果并不对,是一个有小数点后有6个零的一长串数,有时候距离现在更远的时间得到的时间差反而更小,很奇怪。
所以减法还是不要随便乱用的好,原来mysql里有一个计算时间间隔的函数 TIMESTAMPDIFF()
TIMESTAMPDIFF(
unit
,datetime_expr1
,datetime_expr2
)
Returns datetime_expr2
– datetime_expr1
, where datetime_expr1
and datetime_expr2
are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00'
where necessary. The unit for the result (an integer) is given by theunit
argument. The legal values for unit
are the same as those listed in the description of the TIMESTAMPADD()
function.
ABS( TIMESTAMPDIFF(SECOND, log_time, NOW()) )
得到想要的结果了。