我正在尝试根据相关表中的DATETIME列左联接最近的相关记录。

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

我无法在联接中使用子查询来执行此操作,因为返回的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子句中尝试了一个子查询,但这会过滤结果,以便仅返回带有ordersjob。我需要不包含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
)

最佳答案

尝试这个:

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
)

08-04 23:23