MySQL - LEFT JOIN基于datetime列的最新记录

时间:2018-04-04 17:24:37

标签: mysql sql join

根据相关表格中的DATETIME列,我尝试LEFT JOIN最新的相关记录。

最近的记录不是最近插入的记录;日期列定期更新,这是我想加入的日期。

我无法在联接中使用子查询,因为返回的job_id与最近的submitted日期不对应。

SELECT o.id, j.submitted, j.id AS job_id
FROM orders o
LEFT JOIN (
    SELECT id, order_id, MAX(submitted) AS submitted
    FROM jobs
    GROUP BY order_id
) j ON j.order_id = o.id

我还尝试在WHERE子句中使用子查询,但这会过滤结果,以便只返回orders job。我需要ordersjobs没有作为结果集的一部分。

SELECT o.id, j.submitted, j.id AS job_id
FROM orders o
LEFT JOIN jobs j ON j.order_id = o.id
WHERE j.submitted = (
    SELECT MIN(submitted)
    FROM jobs
    WHERE order_id = o.id
)

4 个答案:

答案 0 :(得分:0)

试试这个:

SELECT o.id, j.submitted, j.id AS job_id
FROM orders o
LEFT JOIN jobs j ON j.order_id = o.id
WHERE j.submitted = (
    SELECT MAX(submitted) FROM jobs
)

答案 1 :(得分:0)

这个怎么样?

SELECT o.id, max(j.submitted), j.id AS job_id
FROM orders o
LEFT JOIN jobs j on (j.order_id = o.id)
GROUP BY o.id, j.id
ORDER BY o.id

查询将输出每个订单及其最近的作业。如果它没有相关的工作,那么提交的和工作列将被删除。

答案 2 :(得分:0)

尝试此查询

    SELECT 
    o.id AS orderId, recentOrderInner.*
FROM
    orders o
        LEFT JOIN
    (SELECT 
        j.order_id, j.submitted AS recent_order
    FROM
        job j
    LEFT JOIN job j_l ON (j.order_id = j_l.order_id
        AND j.submitted < j_l.submitted)
    WHERE
        j_l.submitted IS NULL
    ORDER BY aul.created DESC) AS recentOrderInner ON o.id = recentOrderInner.order_id

答案 3 :(得分:0)

执行此操作的正确方法是使用两个连接,而不是一个:

select . . . 
from orders o left join
     jobs j
     on o.id = j.order_id left join
     (select j2.order_id, max(j2.submitted) as max_submitted
      from jobs j2
      group by j2.order_id
     ) j2
     on j2.order_id = j.order_id and j2.max_submitted = j.max_submitted;