ORDER BY字符串(可以是数字或字符串)将空字符串放在MySQL上

时间:2014-04-08 21:15:43

标签: mysql sql string numbers sql-order-by

订购餐桌时遇到问题。

我有一列字符串。这些字符串可以是数字(整数)。

现在我想按升序排序,在顶部留下数字,在底部留下字符串,空的留在最后:

12
23
28
33
Hello
Hello again
(empty string)
(empty string)

这是问题所在,如果我选择:

ORDER BY column ASC

这种情况发生了:

(empty string)
(empty string)
12
23
28
33
Hello
Hello again

我尝试过:

ORDER BY CAST(column as unsigned) ASC, column ASC/DESC

但它将数值放在底部:

Hello again
Hello
(empty string)
(empty string)
(empty string)
12
23
28
33

我该如何解决?非常感谢你!

1 个答案:

答案 0 :(得分:1)

order by 
case 
when column is null then 1 else 0 
end, 
column

OR

  ORDER BY ISNULL(column), column ASC;

OR

  ORDER BY if(column = '' or column is null,1,0),column