sql排序数字然后按字母顺序排列

时间:2010-10-06 21:52:22

标签: php sql mysql natural-sort

在这个例子中

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(值),但按字母顺序排列不起作用

2 个答案:

答案 0 :(得分:2)

如果您可以在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

答案 1 :(得分:1)

好的,感谢评论者,现在是一个工作版本。这按顺序对两个案例进行排序:

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,然后是其他东西,最后是几个月。第二种情况如果可能,将列转换为十进制。