按数字顺序,然后是字母,然后是空值

Kei*_*ith 0 mysql php

我的数据库中有以下列:

abc
1
2
null
100
6
Run Code Online (Sandbox Code Playgroud)

我想按照以下顺序对这些值进行排序和显示:

1
2
6
100
abc
null
Run Code Online (Sandbox Code Playgroud)

任何人请帮我解决它。考虑以下查询:

select * from test_table where status=1 order by test_column DESC
Run Code Online (Sandbox Code Playgroud)

或者

 select * from test_table where status=1 order by if((test_column = '' OR test_column IS NULL),'999999',test_column) DESC
Run Code Online (Sandbox Code Playgroud)

tom*_*bom 5

select
*
from
t
order by
case 
when col regexp '^[0-9]' then 1
when col regexp '^[a-zA-Z]' then 2
when col = '' or col is null then 3
end
, col * 1 /*this converts to number, so that 100 is not sorted before 2*/
, col /*finally sort strings correctly*/
Run Code Online (Sandbox Code Playgroud)

  • 字符串值可以包含数字或其他非字母符号('1a'、'b2'、'a b'、'1+2' 等)。我认为将 `then 2` 移到 `else` 部分更安全。并且数字的正则表达式是`regexp '^[0-9]+$'` 以避免将 '123abc' 视为数字。 (2认同)