mysql SQL:首先要对特定项目进行排序,然后对其余项目进行排序


79

可以说我有下表。

我想得到所有的朋友,但我希望ID 5成为列表中的第一项。我不在乎收到其余物品的顺序。

所需的查询结果将是:

friends
-------

id    name

5     nahum
1     moshe
2     haim
3     yusuf
4     gedalia
6     dana

我怎样才能做到这一点?

使用Mysql5.1.x。

谢谢!

Answers:


147
select id,name 
from friends 
order by id=5 desc

(假设您不关心其余的顺序,否则,例如,通过id asc进行休息

select id,name 
from friends 
order by id=5 desc, id asc

10
@ maxx777这个问题标记为MySQL,现在归Oracle所有。不像Microsoft SQL Server中那样是“ sql-server”。
RichardTheKiwi 2014年

1
我认为大多数查询都适用于所有DBMS。而且,如果有人说该查询不适用于特定的DBMS,通常他会要求该特定DBMS的解​​决方案。
2014年

8
@ maxx777这就是为什么我们有标签和单独的问题。它为提问者解决了他的MySQL问题。如果您要使用SQL Server 2005,则另一个答案也可以,无需评论显然该答案对从未宣传过的内容无效。
RichardTheKiwi 2014年

48

试试这个:

select id,name 
from friends 
order by case when id=5 then -1 else id end

如果您有更多然后可以做的话:

select id,name 
from friends 
order by case when id in (5,15,25) then -1 else id end,id

4

我现在无法访问MySQL进行测试,因此可能会被逆转...但是您可以使用以下事实:布尔值也可以排序,并且可以有多个排序字段。

SELECT ... ORDER BY id != 5, id

(您可能必须编写id = 5,我不记得TRUE是在FALSE之前还是之后排序。)

编辑:哦,我刚刚读到您不关心其余顺序,在这种情况下,我衷心推荐@Richard的答案。


3
我更喜欢id=5 desc,因为当列中包含空值时,!=5将空值放在第一位
RichardTheKiwi 2011年

2

如果要对UNION查询执行相同的操作,例如,如果您具有:

select id,name 
from friends 
UNION
select id,name 
from friends 
order by id=5 desc

...您将在PostgreSQL中得到一个例外:

只能使用结果列名称,不能使用表达式或函数。提示:将表达式/函数添加到每个SELECT,或将UNION移入from子句

要解决此问题,您可以使用以下方法:

select id,name, (id=5) AS is_five
from friends 
UNION
select id,name, (id=5) AS is_five
from friends 
order by is_five DESC, id DESC

表达式(id = 5)将返回't'或'f',具体取决于您的列值是否等于期望值(5),因此,排序依据将首先对't'列进行排序,然后对休息。


2

您应该使用MySQL的ORDER BY FIELD子句解决此问题。尽管答案已经被接受,但这是一个更好的解决方案。

select 1 id, 'Zeta' order_col union all
select 2 id, 'Alpha' order_col union all
select 3 id, 'Gamma' order_col union all
select 4 id, 'Phi' order_col union all
select 5 id, 'Delta' order_col union all
select 6 id, 'Delta' order_col union all
select 7 id, 'Alpha' order_col union all
select 8 id, 'Gamma' order_col union all
select 9 id, 'Zeta' order_col union all
select 10 id, 'Phi' order_col 
order by field (order_col, 'Alpha', 'Gamma', 'Phi', 'Delta', 'Zeta'), id;

这比

  • id =某物,按ID asc排序
  • 当某物然后为1时按情况排序

1
不知道为什么这被否决了。我想知道为什么按字段应该是更好,但答案很有意思..
约翰

@John-这更好,主要是因为易于阅读。另外,这是MySQL提供给我们的一种解决方案。在我看来,当您必须在列中指定许多值的顺序时,这更有意义。
MontyPython '18

1
我认为人们根本不理解您提供了“全部联合”示例以及ORDER BY字段的问题解决方案。因此,下降投票是由于无能。
约翰(John)


2

您可以field()在MySQL中使用。

select id,name from friends order by field(id,5,id)

field()中的第一个参数表示您要与之排序的字段,其余为排序。

所以5将首先排序,其余的将根据id排序(不带5)。field(id,5,1,3,id)如果您想让5,1,3位于最前面,可以这样做。

最后可以选择5个排序field(id,id,5)。第二个ID也将从其中排除5个。


-7

这有点丑陋,因为它具有代码重复功能,但是可以做到这一点:

select .... where id = 5 
union
select .... where not id = 5

2
如果在合并后仍然保持行的顺序,那只是偶然。如果指定order by,它将对整个联合进行排序。
2011年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.