Home  >  Q&A  >  body text

Get the latest row of data

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粉277464743P粉277464743181 days ago351

reply all(1)I'll reply

  • P粉755863750

    P粉7558637502024-04-03 12:13:54

    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

    reply
    0
  • Cancelreply