2013-02-20 53 views
6

說我有以下結果:排序MySQL字符串結果沒有定義的排序規則?

Mackay 
Mackay Airport 
Melbourne 
Melbourne Airport 
Sydney 
Sydney Ac 
Sydney Airport 

我怎樣才能使它所以他們與機場總是在他們的上方有序?按字母順序排列,例如:

Mackay Airport 
Mackay 
Melbourne Airport 
Melbourne 
Sydney Airport 
Sydney 
Sydney Ac 

對如何使機場更加突出有點困惑。

+1

您是否僅考慮「機場」或任何字母數字詞? – Slowcoder 2013-02-20 00:14:35

+5

這不是1NF - 你應該創建一個額外的屬性isAirport' – 2013-02-20 00:29:18

回答

2

不知道下面的查詢涵蓋了所有的情況,但似乎與您的樣本數據進行工作:

select name, 
SUBSTRING_INDEX(name,'Airport',1) 
as l, 
LOCATE('Airport',name) as r from 
(
select 'Sydney Airport' as name 
union all 
select 'Sydney' 
union all 
select 'Sydney Ac' 
union all 
select ' 
Mackay Airport' 
union all 
select 'Mackay' 
union all 
select 'Melbourne' 
union all 
select 'Melbourne Airport' 
)a 
order by l asc, r desc 

與表它看起來像

select name 
from table1 
ORDER BY SUBSTRING_INDEX(name,'Airport',1) ASC, 
LOCATE('Airport',name) DESC 
+0

whoa,查詢比手工排序難得多:-) – 2013-02-20 00:26:49

+0

:)所有'FROM'中的'union's只是爲了運行測試而不創建桌子...... – a1ex07 2013-02-20 00:29:21

1

看來,你可以不能同時按整數和字符串排序,但可以根據「Airport」是否存在來導出要排序的字符串。這是愚蠢的,但它的工作原理:

ORDER BY IF(name NOT LIKE '% Airport', CONCAT(name, ' Birport'), name) 
+1

嗯...'Beerport'會冷卻20% – 2013-02-20 00:33:24

0

下面的查詢會給你期望的輸出(即使查詢是複雜的)。

SELECT t.name 
FROM (
SELECT @num := IF(@num IS NULL, 1, @num+1) AS number, name 
FROM places 
ORDER BY IF ((name LIKE '% Airport'), SUBSTRING(name, 1, LOCATE(' Airport', name) - 1), name)  DESC) t 
ORDER BY t.number DESC; 

這裏是例子。

http://www.sqlfiddle.com/#!2/117b7/80