gpt4 book ai didi

如果使用 TIMESTAMPDIFF 第二个参数为 NULL,MySQL 如何获取时差?

转载 作者:行者123 更新时间:2023-11-29 06:11:44 28 4
gpt4 key购买 nike

我有一个表,其中包含故障时间和几台机器的相应启动时间,以跟踪它们的停机时间。

machine_status(
id integer auto_increment,
machine_no integer,
fail_time datetime,
start_time datetime)

我能够得到每台机器的总停机时间

SELECT machine_no, SUM(TIMESTAMPDIFF(SECOND, fail_time, start_time)) duration
from machine_status
GROUP BY machine_no

但是,如果在执行查询时机器停机,start_time 为 NULL。在这种情况下,我想将当前时间戳替换为 start_time,然后获取时差。

基本上我该如何做这样的事情?

SELECT machine_no, SUM(TIMESTAMPDIFF(SECOND, fail_time, 
IF start_time IS NULL THEN NOW() ELSE start_time)) duration
from machine_status
GROUP BY machine_no

最佳答案

这应该可以完成工作

SELECT
ms.machine_no AS machine_no,
SUM(
TIMESTAMPDIFF(SECOND, ms.fail_time, IFNULL(ms.start_time, NOW()) )
) AS duration
FROM machine_status AS ms
GROUP BY ms.machine_no

关于如果使用 TIMESTAMPDIFF 第二个参数为 NULL,MySQL 如何获取时差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895902/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com