【发布时间】:2020-05-23 07:46:42
【问题描述】:
我正在尝试计算从 start_time 到 end_time 的持续时间,因此我使用 SUBTIME(TIME(end_time), TIME(start_time)) as duration 查询,它在 start_time 和 end_time 都在同一天之内时效果很好。
这是创建 MRE 的代码:
create table mre(
id int,
start_time datetime,
end_time datetime,
desired VARCHAR(40)
);
insert into mre (id, start_time, end_time, desired)
values
(1, "2019-10-10 23:59:59", "2019-10-11 00:01:01", "no"),
(2, "2019-10-10 22:11:11", "2019-10-10 23:11:11", "yes"),
(3, "2019-10-10 11:00:59", "2019-10-10 13:43:01", "yes"),
(4, "2019-10-10 23:57:59", "2019-10-11 00:00:01", "no");
所以现在当我跑步时
select
*,
subtime(time(end_time), time(start_time)) as duration
from mre;
输出
id start_time end_time desired duration
1 2019-10-10 23:59:59 2019-10-11 00:01:01 no -23:58:58
2 2019-10-10 22:11:11 2019-10-10 23:11:11 yes 01:00:00
3 2019-10-10 11:00:59 2019-10-10 13:43:01 yes 02:42:02
4 2019-10-10 23:57:59 2019-10-11 00:00:01 no -23:57:58
第一行从 2019 年 10 月 10 日开始,到 2019 年 10 月 11 日结束。如果你看一下时间,两者之间的差异应该是 00:01:02,这就是我想要的。
但它给了我00:01:01 - 23:59:59 = -23:58:58.
end_time 和 start_time 的切换位置没有意义(我已经尝试过以防万一)。
谁能帮忙?
提前致谢!
编辑:我刚刚发现这是因为在 subtime 函数中我将 end_time 和 start_time 与 TIME() 包装在一起,因此它忽略了日期。
所以我尝试不使用 TIME() 来为持续时间列提供空值。
【问题讨论】:
-
TIMESTAMPDIFF(SECOND,from,to) 怎么样?
-
是的,看来您已经快要自己解决这个问题了
-
@Strawberry 是的,在发布 SO 问题后我一直都在弄清楚。