Get the latest row of data
P粉277464743
P粉277464743 2024-04-02 15:27:20
0
1
384

sheet:

Task: id (bigint) name (varchar). Save task details

Job: id(varchar(UUID)) task_id(bigint(class ID)), staus >(varchar( 50)),created_time (timestamp). Save task execution details

Possible values ​​for status are FAIL/COMPLETED/INTERRUPTED

What I want to achieve is Get all latest values ​​for each task from the job table

If there is no job in the task, the return status is 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粉277464743
P粉277464743

reply all(1)
P粉755863750

For SQL versions that support ROW_NUMBER(), you can do this:

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

Otherwise, just use cte or subquery.

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!