Mysql,复杂的ORDER BY

时间:2010-12-28 14:05:48

标签: mysql

两列城镇和优先权。

我需要对表进行排序,因此优先级为1的城镇将是第一个,而不是按名称ASC排序,而其余的按名称ASC排序。

我该怎么做?

谢谢;)

更新

SELECT *
FROM map_towns
ORDER BY priority DESC, town

像这样,但优先级从1到12+而不是12到1。

就像那样:

town priority
b_town1 1
a_town2 2
d_town3 3
c_town4 4
a_town5 NULL
b_town6 NULL
c_town7 NULL
d_town8 NULL

等...

4 个答案:

答案 0 :(得分:1)

By default, MySQL sorts nulls first

我创建了一个小测试用例(非故意插入的行)。

create table map_towns(
   town varchar(30) not null
  ,priority int null
);

insert into map_towns(town, priority) values('d_town3', 3);
insert into map_towns(town, priority) values('a_town2', 2);
insert into map_towns(town, priority) values('c_town4', 4);
insert into map_towns(town, priority) values('b_town1', 1);
insert into map_towns(town, priority) values('b_town6', NULL);
insert into map_towns(town, priority) values('d_town8', NULL);
insert into map_towns(town, priority) values('a_town5', NULL);
insert into map_towns(town, priority) values('c_town7', NULL);

以下查询应该按照您的要求执行。

select town
      ,priority
      ,isnull(priority) 
 from map_towns 
order by isnull(priority), priority, town;

+---------+----------+------------------+
| town    | priority | isnull(priority) |
+---------+----------+------------------+
| b_town1 |        1 |                0 |
| a_town2 |        2 |                0 |
| d_town3 |        3 |                0 |
| c_town4 |        4 |                0 |
| a_town5 |     NULL |                1 |
| b_town6 |     NULL |                1 |
| c_town7 |     NULL |                1 |
| d_town8 |     NULL |                1 |
+---------+----------+------------------+

以下是ISNULL documentation

上的链接

答案 1 :(得分:0)

我的想法:

SELECT * FROM Towns
ORDER BY IF(priority = 1, 0, 1) ASC,
         town ASC;

答案 2 :(得分:0)

好吧,只需简单地将其设置为默认优先级为0,然后您拥有的每个城镇都可以根据数字对它们进行排序。我通常会做像DisplayOrder这样的事情,这可能是你的优先事项。

像这样的东西。

SELECT * FROM Towns
ORDER BY priority ASC,
name ASC;

所以,如果你有像

这样的东西
id, name, priority
-----------------------
1, Smithtown, 0
2, Rocktown, 2
3, Georgetown, 1
4, Rockton, 2

然后订购

1, Smithtown, 0
3, Georgetown, 1
4, Rockton, 2
2, Rocktown, 2

答案 3 :(得分:0)

SELECT  *
FROM    map_towns
ORDER BY
        priority IS NULL, priority, town