mysql - 存储为文本的两次之间的差异

时间:2015-04-21 16:42:39

标签: mysql sql

我有两个字段 - TimeStart TimeFinish - 在text中存储为sql database。我试图计算两个字段之间的秒数差异,但我在计算的差异字段中得到的是NULL。有什么想法吗?

SELECT TimeStart
    , TimeFinish
    , TIMESTAMPDIFF(SECOND
                   , STR_TO_DATE(TimeFinish, '%h:%i')
                   , STR_TO_DATE(TimeStart, '%h:%i')) AS Difference
FROM table

输出示例

enter image description here

为了尝试解决这个问题,我刚刚使用:

完成了STR_TO_DATE
SELECT TimeStart
    , TimeFinish 
    , (STR_TO_DATE(TimeFinish, '%H:%i:%s')) AS Finish
    , (STR_TO_DATE(TimeStart, '%H:%i')) AS START 
FROM table

得到了这个:

enter image description here

所以有些事情正在发挥作用。

2 个答案:

答案 0 :(得分:1)

如果将值存储为TIME字段,则可以使用以下内容。

SELECT TimeStart, TimeFinish,  
(TIME_TO_SEC(TimeFinish) - TIME_TO_SEC(TimeStart)) AS Difference 
FROM test

答案 1 :(得分:1)

您的方法的第一个问题是"%h"是12小时表示法的小时,需要使用的24小时表示法"%H":

mysql> SELECT STR_TO_DATE(TimeFinish, "%h"), STR_TO_DATE(TimeFinish, "%H") from table;
+-------------------------------+-------------------------------+
| STR_TO_DATE(TimeFinish, "%h") | STR_TO_DATE(TimeFinish, "%H") |
+-------------------------------+-------------------------------+
| NULL                          | 21:00:00                      |
+-------------------------------+-------------------------------+
1 row in set, 2 warnings (0.00 sec)

虽然它本身并没有帮助,TIME_DIFFERENCE仍然会返回NULL。为了解决这个问题,您可以将其替换为TIME_TO_SEC,并计算它们的差异:

mysql> select TimeStart, TimeFinish, TIME_TO_SEC(STR_TO_DATE(TimeFinish, '%H:%i')) - TIME_TO_SEC(STR_TO_DATE(TimeStart, '%H:%i')) as Difference from moo;
+-----------+------------+------------+
| TimeStart | TimeFinish | Difference |
+-----------+------------+------------+
| 21:45     | 21:47      |        120 |
+-----------+------------+------------+
1 row in set (0.00 sec)