我试图计算从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的位置是没有意义的(我已经试过了,以防万一)。
有人能帮上忙吗?
提前感谢!
EDIT:我刚刚知道这是因为在subtime函数中,我用TIME()包装了end_time和start_time,因此它忽略了日期。
所以我试着用TIME()来做这件事,它为duration列提供了空值。
发布于 2020-02-07 15:41:31
我刚刚意识到名称SUBTIME中有" time“,这可能表明它只考虑时间,因此它要求我将time包装在Time()中,并在我尝试插入datetime对象时给出空值。
多亏了https://www.w3resource.com/mysql/date-and-time-functions/mysql-timediff-function.php,我发现当你想在计算持续时间时也考虑日期时,你需要使用TIMEDIFF()函数。
我没有发现关于这个问题的问题(可能太简单了),所以我决定保持开放。
发布于 2020-02-07 16:42:12
select
*,
TIMEDIFF(end_time, start_time) as duration
from mre;或
select
*,
SEC_TO_TIME(TIMESTAMPDIFF(SECOND, start_time, end_time)) as duration
from mre;如果duration超过838:59:59 (35天),则它将被截断为此值(时间数据类型限制)。
https://stackoverflow.com/questions/60108940
复制相似问题