【问题标题】:Get TIMEDIFF() in MySQL from all rows从所有行中获取 MySQL 中的 TIMEDIFF()
【发布时间】:2021-01-10 14:04:11
【问题描述】:

我有一个像这样的user_tasks 表:

| id | user_id | created_at          | status   |
-------------------------------------------------
| 1  | 1       | 2020-08-04 13:00:00 | started  |
| 2  | 1       | 2020-08-04 13:00:00 | pending  |
| 3  | 1       | 2020-08-04 13:00:10 | pending  |
| 4  | 1       | 2020-08-04 13:00:40 | pending  |
| 5  | 1       | 2020-08-04 13:00:41 | finished |

我想以秒为单位获取最后一个pending 状态和第一个pending 状态之间的差异。因此我有这个查询:

SELECT 
    TIMEDIFF(
    (SELECT created_at FROM user_tasks WHERE user_id = 1 AND `status` = 'pending' ORDER BY created_at DESC LIMIT 1), 
    (SELECT created_at FROM user_tasks WHERE user_id = 1 AND `status` = 'pending' ORDER BY created_at ASC LIMIT 1)
    ) AS pending_time

这让我在几秒钟内得到结果(-00:00:40),正如预期的那样。但是,我怎样才能为每个user_task 实现这一目标?

最终,我试图在几秒钟内从所有 user_tasks 中获得平均 pending_time

【问题讨论】:

    标签: mysql sql datetime max min


    【解决方案1】:

    如果我没听错,你可以使用聚合:

    select user_id, timediff(max(created_at), min(created_at)) pending_time
    from user_tasks
    where status = 'pending'
    group by user_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      相关资源
      最近更新 更多