表格:
任务:id(bigint)名称(varchar)。保存任务详细信息
作业:id(varchar(UUID)) task_id(bigint(类 ID)),staus >(varchar(50)),created_time(时间戳)。保存任务执行详情
状态的可能值为 FAIL/COMPLETED/INTERRUPTED
我想要实现的是 从作业表中获取每个任务的所有最新值
如果任务中不存在作业,则返回状态为 null
SELECT p.id, j.status FROM tas p inner JOIN job j ON j.task_id = p.id inner JOIN job j1 ON j.task_id = j1.task_id and j.create_time > j1.create_time;
P粉7558637502024-04-03 12:13:54
对于支持 ROW_NUMBER()
的 SQL 版本,您可以这样做:
WITH info as( SELECT p.id, j.status, ROW_NUMBER() OVER(PARTITION BY p.id ORDER BY j.created_time DESC) AS rn FROM tas p LEFT JOIN job j ON j.task_id = p.id ) SELECT id, status FROM info WHERE rn = 1
否则,只需使用 cte 或子查询。
SELECT p.id, t.status FROM tas AS p LEFT JOIN ( SELECT task_id, MAX(created_time) as created_time FROM job GROUP BY task_id ) as lt ON p.id = lt.task_id LEFT JOIN task AS t ON lt.task_id = t.task_id AND lt.created_time = t.created_time