2014-12-02 44 views
1

我有MySQL查詢使用ORDER BY看起來像這樣:MySQL的ORDER BY字母則數字

ORDER BY home_status = 2, home_lot_size, home_status ASC, home_price 

現在home_lot_size可以是排屋,30,36,40,46,50,但該命令一弄成這樣,30,36,40,46,50,然後排屋,我期待在上面得到排屋然後在30,36,40,46,50

這可能嗎?

+0

是** **排屋在表中僅字符串? – 2014-12-02 15:38:36

回答

2

您可以使用CASE子句創建一個可以排序的新列。這樣

SELECT 
    CASE home_lot_size 
    WHEN 'Townhome' THEN '00' 
    ELSE home_lot_size 
    END as sort_by 
FROM table 
ORDER BY sort_by 
0

可以在ORDER BY使用CASE

ORDER BY home_status = 2, 
     case when home_lot_size = 'Townhome' then '0' else home_lot_size end, 
     home_status ASC, home_price 
0

是的,這是可能的。一個快速修復。將已home_lot_size在數值上下文,使得Townhome值將爲零來評估,而另一個值作爲整數進行評價。一個簡單的方法就是增加零,例如

ORDER BY home_status = 2, home_lot_size + 0, home_status, home_price 
             ^^^ 

在更一般的情況下,我們可以使用更復雜的一系列表達式,例如,

ORDER BY home_status = 2 
     , IF(home_lot_size='Townhome',0,1) 
     , home_lot_size 
     , home_status 
     , home_price 
1

的東西在這裏是一個簡單的解決方案,

SELECT * FROM your_table_name WHERE (home_lot_size='Townhome' OR 1=1) ORDER BY home_lot_size='Townhome' DESC 

你並不需要使用情況下這一點。

+0

我甚至不知道你可以通過+1做到這一點與秩序 – Anurag 2016-02-11 09:20:33