【问题标题】:Mysql SUBTIME(time(end), time(start)) giving negative valueMysql SUBTIME(time(end), time(start)) 给出负值
【发布时间】: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 问题后我一直都在弄清楚。

标签: mysql datetime


【解决方案1】:
select 
  *,
  TIMEDIFF(end_time, start_time) as duration
from mre;

select 
  *,
  SEC_TO_TIME(TIMESTAMPDIFF(SECOND, start_time, end_time)) as duration
from mre;

fiddle

如果duration 超过 838:59:59(35 天),那么它将被截断为此值(TIME 数据类型限制)。

【讨论】:

    【解决方案2】:

    我刚刚意识到 SUBTIME 名称中包含“TIME”,这可能表明它只考虑时间,因此它要求我将时间包装在 Time() 中,并在我尝试插入 datetime 对象时给出空值。

    感谢https://www.w3resource.com/mysql/date-and-time-functions/mysql-timediff-function.php 我发现当你想在计算持续时间时考虑日期时,你需要使用 TIMEDIFF() 函数。

    我没有发现关于这个问题的 SO 问题(可能太简单了)所以我决定保持开放。

    【讨论】:

    • 你不会打扰什么?不会费心让它保持打开状态吗?
    • hm... 我找不到关于 SO 的问题,但是关于这个问题有很多资源,所以关闭它?
    • 我会保持打开状态,因为每当出现问题时我倾向于在 SO 中搜索,但如果有人发现有关此问题的重复问题,我愿意关闭它。 @草莓谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多