从所有行中获取TIMEDIFF在MySQL中

问题描述

我有一个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实现这一目标?

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

解决方法

如果我正确地跟随您,则可以使用汇总:

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