2017-05-23 52 views
2

我需要執行特定的SQL查詢。 例如,我們有一個表名爲people這個表有這樣的記錄:Sql - 按特定順序選擇

- João (id ->1) 
- Telmo (id ->2) 
- Maria (id ->3) 
- Henrique (id ->4) 
- Pedro (id ->5) 

我會獲得一個特定的人,例如我得到henrique id 4選擇了給我看這個名單:

- Henrique 
- Maria 
- Telmo 
- João 
- Pedro 

而且我還需要做相反的訂單

- Henrique 
- Pedro 
- João 
- Telmo 
- Maria 

我該怎麼做?

謝謝

回答

0

使用

select `name` from `table_name` order by find_in_set(id,'4,3,2,1,5'); 

,並得到逆列表,使用:

select `name` from `table_name` order by find_in_set(id,'4,5,1,2,3'); 
2

使用CASE WHEN檢查名稱:

select name 
from mytable 
order by case when name = 'Henrique' then 1 else 2 end, id; 

而且的當然

select name 
from mytable 
order by case when name = 'Henrique' then 1 else 2 end, id desc; 

爲與亨裏克相反的順序仍然第一。

如果你的ID,而不是名稱,然後

order by case when id = 4 then 1 else 2 end, id [desc]; 
+0

我沒有得到正確的 清單。 @ThorstenKettner – user3242861

+0

如果我把id <= 4工作正常!謝謝@ThorstenKettner – user3242861

+0

爲什麼'<= 4'?我以爲只有ID ** = ** 4纔會被特別對待。 –

1

您可以使用UNION運營商把所有的人< =該ID和所有的人> ID,例如:

SELECT name FROM table WHERE id >= 4 ORDER BY id DESC 

UNION 

SELECT name FROM table WHERE id > 4 ORDER BY id 
0

你可以只添加關閉ORDER BY name,如果你想查詢誰在你的名字從你的第一個字母的遞減順序的結果