表格:
任務: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