在mysql中排序与Alpha数值混合的数值

时间:2019-09-02 05:47:50

标签: mysql codeigniter stored-procedures

我有一列居民号码为

res_no
b1
a2
b11
c25
a11
a3
....

我想对这些值进行排序

a2
a3
a11
b1
b11
c25 
...

尝试查询

ORDER BY CAST(substr(res_no,3) as UNSIGNED) asc 

ORDER BY CAST(res_no as UNSIGNED) asc 

但没有什么像上面的答案

1 个答案:

答案 0 :(得分:2)

如果这是您的确切格式,则只需按第一个字母,然后按数字部分(从字母2开始)排序:

SELECT *
FROM table1
ORDER BY LEFT(res_no, 1),
         CAST(SUBSTR(res_no, 2) AS UNSIGNED);

输出:

res_no
a2
a3
a11
b1
b11
c25

Demo on dbfiddle

如果您正在运行支持REGEXP_SUBSTR的MySQL(或MariaDB)版本,则可以更灵活地选择前导字母的数量,甚至字母的结尾或结尾。根本不存在:

SELECT *
FROM table1
ORDER BY res_no REGEXP ('^[0-9]') DESC,
         CAST(res_no AS UNSIGNED),
         REGEXP_SUBSTR(res_no, '(^[a-zA-Z]+)|([a-zA-Z]$)'),
         CAST(REGEXP_SUBSTR(res_no, '(^[0-9]+)|([0-9]+$)') AS UNSIGNED)

Demo on dbfiddle