[英]MySQL ORDER BY one column and a second column
My question is different but I have read this similar SO post: How can I order by two columns, if result is equal, consider another column? 我的问题不同,但是我已经读过类似的文章: 如何按两列排序,如果结果相等,请考虑另一列?
I am interested in 2 columns: 我对2栏感兴趣:
The query is: 查询是:
SELECT BATCH_ISSUED.production_id, MANUFACTURE_DATE.date
FROM BATCH_ISSUED LEFT JOIN
MANUFACTURE_DATE
ON BATCH_ISSUED.production_id = MANUFACTURE_DATE.production_id
WHERE MANUFACTURE_DATE.active='1'
ORDER BY MANUFACTURE_DATE.date ASC,BATCH_ISSUED.production_id ASC
This fetches the data and sorts it by date (old > new) and then sorts by id
but it needs to group all of the same id
together which may mean GROUP BY needs to be included somehow. 这将获取数据并按日期(旧>新)进行排序,然后按
id
进行排序,但是它需要将所有相同的id
分组在一起,这可能意味着需要以某种方式包含GROUP BY。
An example of the data: 数据示例:
195 2017-10-10
196 2017-10-10
196 2017-10-10
258 2017-10-10
258 2017-10-10
189 2017-10-12
190 2017-10-12
258 2017-10-12
212 2017-10-13
213 2017-10-13
It should be presented like this, for example with the ID 258 kept together in date order: 应该这样显示,例如ID 258按日期顺序排列在一起:
195 2017-10-10
196 2017-10-10
196 2017-10-10
258 2017-10-10
258 2017-10-10
258 2017-10-12
189 2017-10-12
190 2017-10-12
212 2017-10-13
213 2017-10-13
Many thanks for any suggestions! 非常感谢您的任何建议!
足以按顺序反转您的订单:
ORDER BY BATCH_ISSUED.production_id DESC, MANUFACTURE_DATE.date ASC,
First, your WHERE
clause turns the OUTER JOIN
to an INNER JOIN
. 首先,您的
WHERE
子句将OUTER JOIN
转换为INNER JOIN
。 As a result, the JOIN
is not even needed. 结果,甚至不需要
JOIN
。 So your query is equivalent to: 因此,您的查询等同于:
SELECT md.production_id, md.date
FROM MANUFACTURE_DATE md
WHERE md.active = 1
ORDER BY md.date ASC, md.production_id ASC;
Then you can use a JOIN
to get the information you want: 然后,您可以使用
JOIN
获取所需的信息:
SELECT md.production_id, md.date
FROM MANUFACTURE_DATE md JOIN
(SELECT md2.production_id, MIN(md2.date) as mind
FROM MANUFACTURE_DATE md2
WHERE md.active = 1
GROUP BY md2.production_id
) mmd
ON md.production_id = md2.production_id
WHERE md.active = 1
ORDER BY mdd.mind ASC, md.production_id ASC, md.date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.