我有orders表和order_histories表。我需要按ordersorder_histories.created_at进行排序,但只对那些order_histories具有state_to = 'submitted'order进行排序。
order_histories有多个submitted并且可能没有submitted。它也可能有多个MAX(order_histories.created_at)-在这种情况下,我对最后一个感兴趣(因此orders)。
我想到的是下面。但是,这是不够的,因为不包括不包括submittedorder_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/

10-11 17:42