我的表中有一个包含各种条目的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
答案 0 :(得分: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)
答案 1 :(得分: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)
这适用于任意初始字符串。它假设在初始字符串和数字之间有一个空格。