带有数字的SQL ORDER BY字符串

时间:2016-08-02 07:27:46

标签: mysql sql sql-order-by

我希望标题为oder,以数字开头,是数字和字符串的组合。

示例数据:

title
------------
1 Blub
2 Blub
3 Blub
4 Blub
5 Blub
6 Blub
7 Blub
8 Blub
9 Blub
10 Blub
11 Blub
12 Blub
13 Blub

默认ORDER BY title告诉我:

1 Blub
10 Blub
11 Blub
12 Blub
13 Blub
2 Blub
20 Blub
21 Blub

是否可以通过数字值获得正确的ORDER BY

1 Blub
2 Blub
10 Blub
11 Blub
12 Blub
13 Blub
20 Blub
21 Blub

4 个答案:

答案 0 :(得分:3)

ORDER BY CONVERT(INT, SUBSTRING(title, 1, 2))应该可以工作,因为空间会被忽略。如果您的数字高于99,则无法工作。

答案 1 :(得分:1)

试试这个:

select *
from yourtable
order by (title + 0)

Demo Here

答案 2 :(得分:1)

试试这个:

order by cast(LEFT(title,LOCATE(' ',title) - 1) as unsigned)

答案 3 :(得分:1)

这会将您的字段拆分为数字和文本部分,然后按顺序排序。

order by CONVERT(INT, SUBSTRING_INDEX(title, ' ', 1)) ASC, SUBSTRING_INDEX(title, ' ', -1) ASC
相关问题