为什么减号运算符给出的结果与mysql中的TIMESTAMPDIFF()函数不同?

时间:2010-04-02 16:02:33

标签: mysql timestamp math

由于mysql中的TIMESTAMP存储为32位值,表示从1970-jan-1 0:00:00(以秒为单位)的时间间隔,我假设在TIMESTAMP值上使用减号( - )运算符会给出这些值的差异很快。实际上不是:

+---------------------------------------------------------------------+
| TIMESTAMP("2010-04-02 10:30:00") - TIMESTAMP("2010-04-02 10:29:59") |
+---------------------------------------------------------------------+
| 41.000000                                                           |
+---------------------------------------------------------------------+
1 row in set (0.05 sec)

mysql> select timestampdiff(SECOND,TIMESTAMP("2010-04-02 10:30:00"),TIMESTAMP("2010-04-02 10:29:59"));
+-----------------------------------------------------------------------------------------+
| timestampdiff(SECOND,TIMESTAMP("2010-04-02 10:30:00"),TIMESTAMP("2010-04-02 10:29:59")) |
+-----------------------------------------------------------------------------------------+
| -1                                                                                      |
+-----------------------------------------------------------------------------------------+

mysql> select TIMESTAMP("2010-04-02 10:30:00") - TIMESTAMP("2010-04-02 10:30:01") ;
+---------------------------------------------------------------------+
| TIMESTAMP("2010-04-02 10:30:00") - TIMESTAMP("2010-04-02 10:30:01") |
+---------------------------------------------------------------------+
| -1.000000                                                           |
+---------------------------------------------------------------------+

+---------------------------------------------------------------------+
| TIMESTAMP("2010-04-02 10:30:00") - TIMESTAMP("2010-04-02 10:31:00") |
+---------------------------------------------------------------------+
| -100.000000                                                         |
+---------------------------------------------------------------------+

似乎一分钟的差异是100而不是60。

为什么会这样?

3 个答案:

答案 0 :(得分:2)

只是一个疯狂的猜测,但也许你在三种情况下将字符串转换为整数?

20100402103000 - 20100402103100 = -100

20100402103000 - 20100402103001 = -1

20100402103000 - 20100402102959 = 41

另一种情况是正确转换。

答案 1 :(得分:0)

使用的正确函数是UNIX_TIMESTAMP()

TIMESTAMP()返回日期(时间),格式为'2003-12-31 00:00:00'。

此外,使用

也没有错
SELECT TIMESTAMPDIFF(SECOND,NOW(),TIMESTAMP("2010-04-02 19:29:59"));

答案 2 :(得分:0)

我尝试了以下操作并收到NULL

SELECT TIMESTAMPDIFF(SECOND, TIMESTAMP("stopTime"), TIMESTAMP("startTime")) FROM 
paktime WHERE fs = 1 AND employ LIKE "Mike Fowler"