sql的时差。午夜总时间

时间:2013-11-29 06:34:28

标签: mysql sql datetime

这里真的需要一些帮助。

拥有包含以下列的表

startdate, stopdate, starttime, stoptime, totaltime

它们的格式为YYYY-MM-DDHH-MM

我如何以totaltime格式获得HH-MM(有时候开始和停止通过午夜)

由于

2 个答案:

答案 0 :(得分:0)

使用TIMEDIFF将在00:00:00.00000 //格式

返回
TIMEDIFF('2013-11-20 12:01:00', '2010-11-19 12:00:00')

或者你可以转换为秒

TIME_TO_SEC(TIMEDIFF('2013-11-20 12:01:00', '2010-11-19 12:00:00'))

答案 1 :(得分:0)

以这种方式试试

UPDATE table1
   SET totaltime = TIMEDIFF(ADDTIME(stopdate, stoptime), 
                            ADDTIME(startdate, starttime));

这是 SQLFiddle 演示

更新:以下是午夜时间的示例。

mysql> CREATE TABLE Table2
    -> (`startdate` date, 
    ->  `stopdate` date, 
    ->  `starttime` time, 
    ->  `stoptime` time, 
    ->  `totaltime` time);
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO Table2 VALUES
    -> ('2013-11-27', '2013-11-28', '11:00', '00:00', NULL),
    -> ('2013-11-27', '2013-11-28', '00:00', '15:00', NULL),
    -> ('2013-11-27', '2013-11-28', '00:00', '00:00', NULL);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> UPDATE table2
    ->    SET totaltime = TIMEDIFF(ADDTIME(stopdate, stoptime), 
    ->                             ADDTIME(startdate, starttime));
Query OK, 3 rows affected (0.01 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> SELECT * FROM table2;
+------------+------------+-----------+----------+-----------+
| startdate  | stopdate   | starttime | stoptime | totaltime |
+------------+------------+-----------+----------+-----------+
| 2013-11-27 | 2013-11-28 | 11:00:00  | 00:00:00 | 13:00:00  |
| 2013-11-27 | 2013-11-28 | 00:00:00  | 15:00:00 | 39:00:00  |
| 2013-11-27 | 2013-11-28 | 00:00:00  | 00:00:00 | 24:00:00  |
+------------+------------+-----------+----------+-----------+
3 rows in set (0.00 sec)