简体   繁体   English

MySQL JOIN用于对具有一对多关系的表进行排序

[英]MySQL JOIN for sorting a table with a 1 to many relationship

I may need some hand holding here, my SQL knowledge is enough to get by but not amazing, I'll break it down simple as I can. 我在这里可能需要一些帮助,我的SQL知识足以应付,但并不令人惊讶,我将尽可能简单地分解它。

  • I have two tables: orders and shippers 我有两个表: ordersshippers
  • orders has many shippers , related by the orderno column orders有很多shippers ,由orderno列关联
  • shippers has a move_dt column (date/time when the order is going to be shipped) shippers有一个move_dt列(要发货的日期/时间)

I want to sort orders by the highest move_dt in the shippers table. 我想按shippers表格中最高的move_dt排序orders

In other words: I want to list orders by the date/time they are shipping, and only show each order once. 换句话说:我想按发货日期/时间列出订单,并且只显示每个订单一次。

This query gives me multiple instances of orders, one for each shipper it has: 此查询为我提供了多个订单实例,每个实例针对其拥有的每个托运人:

select `orders`.*, `shippers`.`move_dt` from `orders`
join `shippers` on `shippers`.`orderno` = `orders`.`orderno`
order by `shippers`.`move_dt` desc

What do I need to do so each order shows only once? 我需要做什么,所以每个订单只能显示一次? The query should return the same number of results as select * from orders but be sorted by the highest move date in the shippers table. 该查询应返回与select * from orders相同数量的结果,但按托运人表中的最高移动日期排序。

I'm happy to post table structures and any other relevant info, and to have edits to my post that make it more clear. 我很高兴发布表结构和任何其他相关信息,并对我的帖子进行编辑以使其更加清晰。

Approach 1: 方法1:

You can Group By on the orderno field; 你可以Group Byorderno场; this would result in one row per orderno . 这将导致每个orderno一行。 Then, you can use Max() aggregation function to get the maximum move_dt value for an order. 然后,您可以使用Max()聚合函数来获取订单的最大move_dt值。 Eventually, you can sort the result based on the maximum move_dt value. 最终,您可以根据最大move_dt值对结果进行排序。

select o.orderno, -- you can add more columns here from orders table 
       MAX(s.move_dt) AS max_move_dt
from orders AS o 
join shippers AS s on s.orderno = o.orderno
group by o.orderno -- ensure to add extra column from select clause here also
order by max_move_dt desc

Additional Notes: 补充笔记:


Approach 2: 方法二:

We can use a Correlated Subquery and fetch the maximum move_dt value for an order. 我们可以使用相关子查询并获取订单的最大move_dt值。 This will do away with the Group by , and Join requirements. 这将消除“ Group by ”和“ Join要求。 Now, you can specify all the column(s) from the orders table in the Select clause, without worrying about specifying them in the Group By clause: 现在,您可以在Select子句中指定orders表中的所有列,而不必担心在Group By子句中指定它们:

select o.*, 
       (SELECT MAX(move_dt) 
        FROM `shippers` AS s 
        WHERE s.orderno = o.orderno) AS max_move_dt 
from `orders` AS o 
order by max_move_dt desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM