我有orders
表和order_histories
表。我需要按orders
对order_histories.created_at
进行排序,但只对那些order_histories
具有state_to = 'submitted'
的order
进行排序。order_histories
有多个submitted
并且可能没有submitted
。它也可能有多个MAX(order_histories.created_at)
-在这种情况下,我对最后一个感兴趣(因此orders
)。
我想到的是下面。但是,这是不够的,因为不包括不包括submitted
order_history
的。
SELECT orders.*, MAX(order_histories.created_at) AS date
FROM orders
LEFT JOIN order_histories ON order_histories.order_id = orders.id
WHERE order_histories.state_to = 'submitted'
GROUP BY orders.id
ORDER BY date ASC, orders.id DESC
我怎样才能纠正?
最佳答案
外部联接表的条件属于ON
子句而不是WHERE
子句:
SELECT orders.*, MAX(order_histories.created_at) AS date
FROM orders
LEFT JOIN order_histories ON order_histories.order_id = orders.id
AND order_histories.state_to = 'submitted'
GROUP BY orders.id
ORDER BY date ASC NULLS LAST, orders.id DESC;
使用
WHERE
子句反而使您的join变成了一个内部join,因为它取消了所有外部join行(即那些没有提交的订单历史记录的行)。关于sql - 按左联接表排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49258852/