简体   繁体   English

在MySQL中有两列的ORDER BY

[英]ORDER BY with two columns in MySQL

I know I can order two columns with 我知道我可以订购两列

ORDER BY col1 DESC, col2 DESC

for example. 例如。

But in my case this doesn't work. 但是对于我来说,这是行不通的。 I have a MySQL-Query, where I want to display events of the next days ordered by date , BUT also by a column named highlight . 我有一个MySQL查询,我想在这里显示按date排序的次日事件,但也要通过名为Highlight的列highlight

Because there are 3 types of events: TOP-Premium (+++), Premium (++) and Free (+). 因为存在3种类型的事件:TOP-Premium(+++),Premium(++)和Free(+)。

Now it orders like this: 现在,它的命令是这样的:

-- < example > -<示例>

7th May 2013

+FREE EVENT
++PREMIUM
+++TOP PREMIUM
+++TOP PREMIUM

-- -

8th May 2013
(same here as on 7th May 2013)

-- < / end of example > -</示例结尾>

So, as you can see, it orders by the next date is coming, which is correct! 因此,正如您所看到的,它要在下一个日期之前下订单,这是正确的! But I want to order the TOP-Premium-Events at the top, followed by the Premium-Events and at least the free events. 但是我想在顶部订购TOP-Premium-Events,然后是Premium-Events,至少是免费事件。

The end of my current non-working query is: 我当前无法正常工作的查询的结尾是:

ORDER BY e.`date` ASC, e.`highlight` ASC");

I appreciate any help or suggestions! 我感谢任何帮助或建议!

Uhm,

ORDER BY e.date ASC, e.highlight DESC

?

ORDER BY e.date DESC,e.highlight ASC

Swap two columns - first order by highlight and then by date. 交换两列-按highlight顺序排列,然后按日期排列。 You will get sequence like: 您将获得如下序列:

Top premium: 7th may
Top premium: 8th may
Premium: 7th may
Premium: 8th may
Free: 7th may
...

ENUMs are represented internally as numbers, in the order that they were listed in the declaration. ENUM在内部以数字表示,按照它们在声明中列出的顺序。 If you declare a column as ENUM('2', '1', '0') , '2' is stored as 1 , '1' as 2 , and '0' as 3 . 如果将列声明为ENUM('2', '1', '0') ,则将'2'存储为1 ,将'1'存储为2 ,将'0'3

ORDER BY uses those internal numbers, not the labels. ORDER BY使用这些内部编号,而不是标签。 If you want to order by the label, rather than the internal number, you have to use CAST() , eg 如果要按标签而不是内部编号排序,则必须使用CAST() ,例如

ORDER BY e.`date` ASC, CAST(e.highlight AS CHAR) ASC

This is one of the reasons why it's usually a bad idea to use numbers as the labels for an ENUM. 这就是为什么将数字用作ENUM的标签通常不是一个好主意的原因之一。 The MySQL documentation recommends against it. MySQL 文档建议不要这样做。

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

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