在mysql中添加两个Time字段将返回null

时间:2014-08-26 18:49:48

标签: mysql phpmyadmin

为什么这样做:

SELECT CAST(CAST('08:00:00' as time) + CAST('06:00:00' as time) as time);
result: 14

而不是这些其他值?

SELECT CAST(CAST('08:30:00' as time) + CAST('06:30:00' as time) as time);
result: NULL

3 个答案:

答案 0 :(得分:2)

因为您在算术上下文中添加了时间:

MariaDB [(none)]> select cast('08:30:00' as time), cast('06:30:00' as time);
+--------------------------+--------------------------+
| cast('08:30:00' as time) | cast('06:30:00' as time) |
+--------------------------+--------------------------+
| 08:30:00                 | 06:30:00                 |
+--------------------------+--------------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> select cast('08:30:00' as time) + cast('06:30:00' as time);
+-----------------------------------------------------+
| cast('08:30:00' as time) + cast('06:30:00' as time) |
+-----------------------------------------------------+
|                                              146000 |
+-----------------------------------------------------+

MariaDB [(none)]> select cast(146000 as time);
+----------------------+
| cast(146000 as time) |
+----------------------+
| NULL                 |
+----------------------+

你不能像这样一起添加时间。试试这个:

MariaDB [(none)]> select cast('08:30:00' as time) + INTERVAL 6 HOUR + INTERVAL 30 MINUTE;
+-----------------------------------------------------------------+
| cast('08:30:00' as time) + INTERVAL 6 HOUR + INTERVAL 30 MINUTE |
+-----------------------------------------------------------------+
| 15:00:00                                                        |
+-----------------------------------------------------------------+
1 row in set (0.00 sec)

答案 1 :(得分:1)

您需要使用ADDTIME:

SELECT ADDTIME(CAST('08:30:00' as TIME), CAST('06:30:00' as TIME));

答案 2 :(得分:0)

要做到这一点,你必须转换时间。基本上它试图将14:60:00转换为时间146000 ..但那将是15:00:00,这就是为什么它返回null。如果您进行转换,那么它将正常运行。

SELECT 
    SEC_TO_TIME(
        TIME_TO_SEC(CAST('08:30:00' as time)) 
      + TIME_TO_SEC(CAST('06:30:00' as time))
    )