1

我的表中有一个 varchar 字段,其中包含各种条目。如何使用 order by 语句获得以下结果:

1
2
3
4
5
6
7
8
9
10
Steinstrass 1
Steinstrass 2
Steinstrass 3
Steinstrass 4
Steinstrass 5
Steinstrass 6
Steinstrass 7
Steinstrass 8
Steinstrass 9
Steinstrass 10
4

2 回答 2

2

这对我有用:

mysql> select * from sorting;
+---------+
| field1  |
+---------+
| 1       |
| 4       |
| 10      |
| Item 1  |
| Item 10 |
| Item 0  |
| 0       |
+---------+
7 rows in set (0.00 sec)

mysql> select field1 from sorting order by length(field1),field1 asc;
+---------+
| field1  |
+---------+
| 0       |
| 1       |
| 4       |
| 10      |
| Item 0  |
| Item 1  |
| Item 10 |
+---------+
7 rows in set (0.00 sec)
于 2012-08-05T15:28:42.797 回答
1

试试这个:

order by (case when left(str, 1) between '0' and '9' then 1
               else 0
          end) desc,
         (case when left(str, 1) between '0' and '9' then cast(str as unsigned)
          end),
         cast(substring(str, instr(' ', str)+1, 100) as unsigned)

这应该适用于任意初始字符串。它假定初始字符串和数字之间有一个空格。

于 2012-08-05T15:38:06.760 回答