timediff功能无法正常工作。在下面的例子中,我试图计算1年期间的差异。
mysql>SELECT 366*24*60*60 AS expected;
+----------+
| expected |
+----------+
| 31622400 |
+----------+
1 row in set (0.00 sec)
mysql>SELECT ABS(UNIX_TIMESTAMP('2000:01:01 00:00:00') - UNIX_TIMESTAMP('2001:01:01 00:00:00'));
+------------------------------------------------------------------------------------+
| ABS(UNIX_TIMESTAMP('2000:01:01 00:00:00') - UNIX_TIMESTAMP('2001:01:01 00:00:00')) |
+------------------------------------------------------------------------------------+
| 31622400 |
+------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql>SELECT TIME_TO_SEC(TIMEDIFF('2000:01:01 00:00:00', '2001:01:01 00:00:00'));
+---------------------------------------------------------------------+
| TIME_TO_SEC(TIMEDIFF('2000:01:01 00:00:00', '2001:01:01 00:00:00')) |
+---------------------------------------------------------------------+
| -3020399 |
+---------------------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
Warning (Code 1292): Truncated incorrect time value: '-8784:00:00'
答案 0 :(得分:5)
编辑:您使用的是哪个版本的MySQL?它至少在5.0.22上工作正常。我刚刚运行了这个查询。看到这里
mysql> SELECT TIME_TO_SEC(TIMEDIFF('2000:01:01 00:00:00', '2001:01:01 00:00:00'));
+---------------------------------------------------------------------+
| TIME_TO_SEC(TIMEDIFF('2000:01:01 00:00:00', '2001:01:01 00:00:00')) |
+---------------------------------------------------------------------+
| -31622400 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
你有see here吗? 可能是截断问题,因为时间范围远小于您拥有的日期差异。
原始答案
使用此
SELECT TIMESTAMPDIFF(SECOND,'2000:01:01 00:00:00', '2001:01:01 00:00:00');
+--------------------------------------------------------------------+
| TIMESTAMPDIFF(SECOND,'2000:01:01 00:00:00', '2001:01:01 00:00:00') |
+--------------------------------------------------------------------+
| 31622400 |
+--------------------------------------------------------------------+
问题是你正在尝试将负时间转换为秒时间。交换变量就可以了。
SELECT TIME_TO_SEC(TIMEDIFF('2001:01:01 00:00:00','2000:01:01 00:00:00'));
+--------------------------------------------------------------------+
| TIME_TO_SEC(TIMEDIFF('2001:01:01 00:00:00','2000:01:01 00:00:00')) |
+--------------------------------------------------------------------+
| 31622400 |
+--------------------------------------------------------------------+