【问题标题】:sql sort numeric then alphabeticallysql按数字排序然后按字母顺序
【发布时间】:2010-10-06 21:52:22
【问题描述】:
在这个例子中:
10-20
20-40
50-60
v
k
r
a
12 month
1 month
我怎样才能按这个顺序排序?:
10-20
20-40
50-60
a
k
r
v
1 month
12 month
我使用 abs(value) 但在字母大小写中不起作用
【问题讨论】:
标签:
php
sql
mysql
natural-sort
【解决方案1】:
如果你可以在 PHP 中做一些处理,你可以使用natsort:
Standard sorting
Array
(
[3] => img1.png
[1] => img10.png
[0] => img12.png
[2] => img2.png
)
Natural order sorting
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)
否则,关于 SO 的另一个问题会问同样的问题:Natural Sort in MySQL
【解决方案2】:
好的,感谢评论者,现在是一个工作版本。这对 order by 子句中的两种情况进行排序:
select *
from (
select '10-20' as col1
union all select '20-40'
union all select '50-60'
union all select 'v'
union all select 'k'
union all select 'r'
union all select 'a'
union all select '12 month'
union all select '1 month'
) s1
order by
case
when col1 rlike '[0-9][0-9]-[0-9][0-9]' then 1
when col1 rlike '[0-9]+ month' then 3
else 2
end
, case
when col1 rlike '[0-9][0-9]-[0-9][0-9]' then cast(col1 as decimal)
when col1 rlike '[0-9]+ month' then cast(col1 as decimal)
else col1
end
第一种情况将类别按顺序排列:首先是 00-00,然后是其他内容,最后是月份。如果可能,第二种情况将列转换为十进制。