2010-12-28 17 views
0

2つの列の町と優先度。Mysql、complex ORDER BY

優先度が1の町が最初になり、残りがASCという名前でソートされないように、テーブルをソートする必要があります。

どうすればいいですか?

おかげ;)

アップデートこのよう

SELECT * 
FROM map_towns 
ORDER BY priority DESC, town 

、しかしように優先順位が1のような

に12+の代わりに、1から12までであった:

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 

など...

+0

上のリンクである...私は完全にあなたの質問を理解してNIT確かです。 – Jaime

+0

ORDER BY優先、town ????? –

+0

私は答えを投稿した後、もう一度質問を再読しました。優先度= 1だけ気にしますか? priority = 1はpriority = 2より前にソートされるべきですか?たとえば、 "a_town2"が優先度= 4を取得し、 "c_town4"が優先度= 2を取得すると、最初に来ますか? – Ronnis

答えて

1

By default, MySQL sorts nulls first

だろう、私は(行が非挿入小さなテストケースを作成しました - puで並べ替えrpose)。

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

+0

まあまあ!ちょうど私が欲しいもの。どのように私はISNULL文を忘れてしまったのでしょうか?基本的に、結果を反復してフラグを生成し、それを並べ替えます。ありがとう ;) – Somebody

0

私の考え:

SELECT * FROM Towns 
ORDER BY IF(priority = 1, 0, 1) ASC, 
     town ASC; 
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 
0
SELECT * 
FROM map_towns 
ORDER BY 
     priority IS NULL, priority, town 
+0

しかし、 "priority <> 1"ソート済みリストはリストの最後にありますが、リストの先頭にある必要があります。ありがとうございます;) – Somebody

+0

@Beck: 'priority <> 1'は' priority = 1'のものの後に置く 'priority'を持つ町では' 1'と評価されます。あなたが望むものではありませんか? – Quassnoi

+0

それは後に配置されていない、それは問題です。他のすべてがうまくいきます。私は優先順位> 1がリストの最初のものである必要があります。 – Somebody