MySQL ORDER BY字母然后是数字

时间:2014-12-02 15:31:39

标签: mysql

我有一个带有ORDER BY的MySQL Query,如下所示:

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

现在home_lot_size可以是Townhome,30,36,40,46,50,但顺序就像这样,30,36,40,46,50和Townhome,我希望Townhome在顶部那么30,36,40,46,50

这可能吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这是一个简单的解决方案,

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

您不需要使用案例。

答案 2 :(得分:0)

您可以在CASE中使用ORDER BY

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

答案 3 :(得分: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