我有一列居民号码为
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
但没有什么像上面的答案
答案 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
如果您正在运行支持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)