MySQL时间函数TIMEDIFF溢出

最近做的公司内部系统,毕竟是菜鸟,遇到各种问题哭

谈谈今天的问题吧

需要统计数据库中两个时间的时间间隔,mentor直接在SQL语句中进行了计算


<span style="font-size:24px;">TIME_TO_SEC(TIMEDIFF(IFNULL(i.resolutiondate,NOW()),i.created))</span>


测试时发现处理后的数据出现了负值,一层层定位bug,最终找到了这里

当时两个日期相差120天,于是第一反应是TIMEDIFF溢出

查看MySQL官方文档的TIMEDIFF函数说明


 TIMEDIFF(expr1,expr2)

TIMEDIFF() returns expr1 – expr2 expressed as a time value. expr1 and expr2 are time or date-and-time expressions, but both must be of the same type.

The result returned by TIMEDIFF() is limited to the range allowed for TIME values. Alternatively, you can use either of the functions TIMESTAMPDIFF() and UNIX_TIMESTAMP(), both of which return integers.


红色字体写明,TIMEDIFF()的返回值范围限定在TIME的范围内

继续查看TIME的文档


MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or 'HHH:MM:SS' format for large hours values). TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).


红色字体写明,TIME值大约在-839H和839H之间,大约是正负35天的样子

由此,猜测得证奋斗


我所采取的解决方案,就是把两个时间戳取到逻辑层,在逻辑层进行操作,使用long类型,妈妈再也不用担心溢出啦


参见:http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timediff

           http://dev.mysql.com/doc/refman/5.7/en/time.html   


你可能感兴趣的:(sql,mysql,数据库,溢出,TIMEDIFF)