我正在尝试将delivery
表的最新值加入delivery_history
表中。为此,我编写了以下查询,但这没有用:
SELECT d.*
FROM delivery as d
LEFT JOIN
(SELECT *
FROM delivery_history
WHERE delivery_history.delivery_id = d.id
ORDER BY id DESC LIMIT 1) h ON d.id = h.delivery_id
WHERE h.delivery_status = 'Pending' GROUP BY d.id
交货表
id | name
1 | John
delivery_history表
id | delivery_id | delivery_status
1 | 1 | Pending
2 | 1 | Invoiced
预期结果
id | name | delivery_status
1 | John | Invoiced
我的查询出了什么问题?
答案 0 :(得分:2)
使用这样的逻辑:
SELECT d.*
FROM delivery d JOIN
delivery_history dh
ON dh.delivery_id = d.id JOIN
(SELECT dh.delivery_id, MAX(dh.id) as max_id
FROM delivery_history dh
GROUP BY dh.delivery_id
) ddh
ON ddh.delivery_id = dh.delivery_id AND ddh.max_id = dh.id
WHERE dh.delivery_status = 'Pending';
我将LEFT JOIN
更改为内部联接,因为您需要匹配WHERE
条件。
编辑:
如果只希望获得最新状态,则使用相关子查询可能更有效:
select d.*,
(select dh.status
from delivery_history dh
where dh.delivery_id = d.id
order by dh.id desc
limit 1
) as latest_status
from delivery d
having latest_status = 'Pending';
答案 1 :(得分:0)
使用max
SELECT d.id, max(h.id)
FROM delivery as d
LEFT JOIN delivery_history h ON h.delivery_id = d.id
WHERE h.delivery_status = 'Pending'
GROUP BY d.id