在mysql中按字母数字排序

时间:2012-10-12 12:18:59

标签: mysql

你能帮帮我吗?

我的查询是

SELECT num FROM sortnum ORDER BY lpad(num, 10, 0) 

此查询的结果并不好 这是结果

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
1a 
2a 
2b 
A1 
A2 
A3 
A4 
B1 
A10 
A11 
B10 

此类数据的最佳查询是什么 我想要数字首先,然后数据以a开头,然后用b

我想要像

这样的结果
1 
1a 
2 
2a 
2b 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
A1 
A2 
A3 
A4 
A10 
A11 
B1 
B10 

提前致谢

2 个答案:

答案 0 :(得分:4)

假设任何字母前缀的长度最多为一个字符,您可以这样做:

SELECT   num
FROM     sortnum
ORDER BY
  CAST(num AS UNSIGNED)=0,     -- those starting with numbers before non-numbers
  CAST(num AS UNSIGNED),       -- then by number prefix (if any)
  LEFT(num,1),                 -- then by first character
  CAST(MID(num,2) AS UNSIGNED) -- then by remaining numbers

sqlfiddle上查看。

答案 1 :(得分:0)

SELECT num,
CONVERT(SUBSTRING_INDEX(num,'-',-1),UNSIGNED INTEGER) AS num
FROM sortnum
ORDER BY num;