在这里我可能需要一些帮助,我的 SQL 知识足以应付但并不令人惊奇,我会尽可能简单地分解它。
- 我有两个表:
orders
和shippers
orders
有很多shippers
,由orderno
列关联shippers
有一个move_dt
列(订单发货的日期/时间)
我想按 shippers
表中最高的 move_dt
对 orders
进行排序。
换句话说:我想按发货日期/时间列出订单,并且每个订单只显示一次。
此查询为我提供了多个订单实例,每个订单对应一个发货人:
select `orders`.*, `shippers`.`move_dt` from `orders`
join `shippers` on `shippers`.`orderno` = `orders`.`orderno`
order by `shippers`.`move_dt` desc
我需要做什么才能使每个订单只显示一次?查询应返回与 select * from orders
相同数量的结果,但按 shippers 表中的最高移动日期排序。
我很乐意发布表格结构和任何其他相关信息,并编辑我的帖子以使其更加清晰。
最佳答案
方法一:
您可以在 orderno
字段上Group By
;这将导致每个 orderno
一行。然后,您可以使用 Max()
聚合函数以获得订单的最大 move_dt
值。最终,您可以根据最大 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
附加说明:
- 不要使用
Select *
;总是喜欢使用要获取的列的名称。请阅读:Why is SELECT * considered harmful? - 当使用
Group By
时,我们需要确保Select
子句中指定的所有列/表达式是聚合表达式,或者是Group By
子句。请阅读:SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by - 建议使用Aliasing在处理多表查询时。
方法 2:
我们可以使用 Correlated Subquery并获取订单的最大 move_dt
值。这将消除 Group by
和 Join
要求。现在,您可以在 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
关于MySQL JOIN 用于对具有一对多关系的表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53160184/