从表中获取所有行 - 使用另一个表中的最新行,使用基于最新行的另一个表

时间:2017-05-31 15:12:46

标签: mysql sql join

我需要从订单表中获取所有详细信息,订单状态表中包含最新状态ID,然后从状态表中获取该状态的名称。

订单

id | customer | product
-----------------------
1  | David    | Cardboard Box

Order_to_statuses

id | order | status | updated_at
--------------------------------
1  | 1     | 1      | 2017-05-30 00:00:00
2  | 1     | 3      | 2017-05-28 00:00:00
3  | 1     | 4      | 2017-05-29 00:00:00
4  | 1     | 2      | 2017-05-26 00:00:00
5  | 1     | 5      | 2017-05-05 00:00:00

order_states

id | name 
---------
1  | Pending
2  | Paid
3  | Shipped
4  | Refunded

在这种情况下,我需要获取customerproduct,其中包含订单状态表中的最新状态ID,然后是该状态的名称。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

首先获取每个max(updated_at)的{​​{1}},然后解决您需要的所有其他问题。您可以使用子查询获取每个订单的最大日期:

order

一旦你得到这个,你现在有订单,状态ID和最近的日期。使用此功能,您可以加入其他表格,进行完整查询:

select  
   s.`order`, 
   s.`status`,
   s.updated_at
from order_to_statuses s
inner join 
(
   select 
       `order`,
       max(updated_at) as updated_at
   from order_to_statuses
   group by `order`
) m
   on s.`order` = m.`order`
   and s.updated_at = m.updated_at

查看the documentation

答案 1 :(得分:0)

它可能有一些拼写错误,但查询的想法应该是这样的:

select orders.id, orders.customer, orders.product, 
       order_to_status.status, staus.name 
from orders, order_to_status, status
where orders.id = order_to_status.order
and order_to_status.status = status.id
and order_to_status.updated_at in (
         SELECT MAX(order_to_status.updated_at)  
         FROM order_to_status
         where order_to_status.order = orders.id
         group by order_to_status.order 
);

我通常不使用连接但是使用连接它应该是这样的:

select orders.id, orders.customer, orders.product, 
       order_to_status.status, staus.name 
from orders
JOIN order_to_status ON orders.id = order_to_status.order
JOIN status ON order_to_status.status = status.id
where 
order_to_status.updated_at in (
    SELECT MAX(order_to_status.updated_at)  
    FROM order_to_status 
    where order_to_status.order = orders.id
    group by order_to_status.order 
);

注意我添加了一个我错过的小组。

编辑2

我在子查询条件中出错了。 已更改为where order_to_status.order = orders.id 还在where子句之后移动了小组。

相关问题