[英]SQL ORDER BY string with number
我想要按標題開頭的字母,以數字開頭,是數字和字符串的組合。
示例數據:
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
ORDER BY CONVERT(INT, SUBSTRING(title, 1, 2))
應該可以工作,因為空間將被忽略。 如果您的數字大於99,則無法使用。
嘗試這個:
order by cast(LEFT(title,LOCATE(' ',title) - 1) as unsigned)
這會將您的字段分為數字和文本部分,然后對其進行排序。
order by CONVERT(INT, SUBSTRING_INDEX(title, ' ', 1)) ASC, SUBSTRING_INDEX(title, ' ', -1) ASC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.