SUB_TIME
描述
从给定的日期时间/时间表达式中减去指定的时间间隔。若第二个参数为负数,则等价于向第一个参数中添加该时间间隔。
语法
SUB_TIME(`<date_or_time_expr>`, `<time>`)
参数
| 参数 | 说明 |
|---|---|
<date_or_time_expr> | 参数是合法的日期表达式,支持输入 datetime/date/time 类型,date 类型会转换为对应日期的一天起始时间 00:00:00 ,具体 datetime//time 格式请查看 datetime 的转换 和 time的转换 |
<time> | 参数为合法的时间表达式,表示从<date_or_time_expr> 中减去的时间值,若为负数,则表示增加,支持输入 time 类型 |
返回值
返回 <date_or_time_expr> 减去 <time> 时间值之后的结果,根据第一个参数类型返回不同的类型
- 若第一个参数为 datetime 类型,则返回 datetime 类型
- 若第一个参数为 time 类型,则返回 time 类型
特殊情况:
- 若输入参数包含 null ,返回 null
- 若第一个参数类型为 time 类型,且计算结果超出 time 类型范围,则返回 time 类型最大(最小值)
- 若第一个参数类型为 datetime 类型,且计算结果超出 datetime 类型,则跑出错误
举例
-- 减少时间当第一个参数为 datetime 类型
SELECT SUB_TIME('2025-09-19 12:00:00', '01:30:00');
+---------------------------------------------+
| SUB_TIME('2025-09-19 12:00:00', '01:30:00') |
+---------------------------------------------+
| 2025-09-19 10:30:00 |
+---------------------------------------------+
-- 减少时间当第一个参数为 time 类型
SELECT SUB_TIME(cast('12:15:20' as time), '00:10:40');
+------------------------------------------------+
| SUB_TIME(cast('12:15:20' as time), '00:10:40') |
+------------------------------------------------+
| 12:04:40 |
+------------------------------------------------+
-- NULL 参数测试
SELECT SUB_TIME(NULL, '01:00:00');
+----------------------------+
| SUB_TIME(NULL, '01:00:00') |
+----------------------------+
| NULL |
+----------------------------+
SELECT SUB_TIME('2025-09-19 12:00:00', NULL);
+---------------------------------------+
| SUB_TIME('2025-09-19 12:00:00', NULL) |
+---------------------------------------+
| NULL |
+---------------------------------------+
SELECT SUB_TIME(NULL, NULL);
+----------------------+
| SUB_TIME(NULL, NULL) |
+----------------------+
| NULL |
+----------------------+
-- time 类型超出范围测试(返回最大/最小值)
SELECT SUB_TIME(cast('835:30:00' as time), '-21:00:00');
+--------------------------------------------------+
| SUB_TIME(cast('835:30:00' as time), '-21:00:00') |
+--------------------------------------------------+
| 838:59:59 |
+--------------------------------------------------+
SELECT SUB_TIME(cast('-832:30:00' as time), '31:00:00');
+---------------------------------------------------+
| SUB_TIME(cast('-832:30:00' as time), '31:00:00') |
+---------------------------------------------------+
| -838:59:59 |
+---------------------------------------------------+
-- datetime 类型超出范围测试(抛出错误)
SELECT SUB_TIME('0000-01-01 00:00:00', '00:00:01');
ERROR 1105 (HY000): errCode = 2, detailMessage = (10.16.10.3)[INVALID_ARGUMENT]datetime value is out of range in function sub_time
SELECT SUB_TIME('9999-12-31 23:59:59', '-00:00:01');
ERROR 1105 (HY000): errCode = 2, detailMessage = (10.16.10.3)[INVALID_ARGUMENT]datetime value is out of range in function sub_time