This is the result of my query, but it doesn't order correctly. I want to order by the last 2 characters. The result should be: Fa0/10 below Fa0/9.
这是我的查询的结果,但它没有正确排序。我想按最后2个字符排序。结果应该是:Fa0 / 10低于Fa0 / 9。
Fa0/1
Fa0/10
Fa0/11
Fa0/12
Fa0/2
Fa0/3
Fa0/4
Fa0/5
Fa0/6
Fa0/7
Fa0/8
Fa0/9
Gi0/1
Gi0/2
Null0
Vlan1
My query:
SELECT inft.port FROM interfaces AS intf ORDER BY RIGHT(intf.port + 0, 2)
second edit: sqlfiddle
第二次编辑:sqlfiddle
4 个解决方案
#1
7
Try this:
SELECT port
FROM interfaces
ORDER BY SUBSTRING_INDEX(port, '/', 1), CAST(SUBSTRING_INDEX(port, '/', -1) AS SIGNED)
Check the SQL FIDDLE DEMO
检查SQL FIDDLE DEMO
OUTPUT
| PORT |
|--------|
| Fa0/1 |
| Fa0/2 |
| Fa0/3 |
| Fa0/4 |
| Fa0/5 |
| Fa0/6 |
| Fa0/7 |
| Fa0/8 |
| Fa0/9 |
| Fa0/10 |
| Fa0/11 |
| Fa0/12 |
| Gi0/1 |
| Gi0/2 |
| Null0 |
| Vlan1 |
#2
6
Why you need + 0
?? Simply remove it and it will work.
为什么你需要+ 0?只需将其移除即可。
SELECT port FROM interfaces ORDER BY RIGHT(port, 2)
SQL小提琴演示
Output:
PORT
------------
Fa0/1
Gi0/1
Gi0/2
Fa0/2
Fa0/3
Fa0/4
Fa0/5
Fa0/6
Fa0/7
Fa0/8
Fa0/9
Fa0/10
Fa0/11
Fa0/12
Null0
Vlan1
#3
1
The order is correct - lexicographically.
订单是正确的 - 按字典顺序排列。
You need to convert them to a number.
您需要将它们转换为数字。
#4
0
UPDATED
You need to do + 0
after extracting last two chars to convert it into number
在提取最后两个字符后,您需要执行+ 0将其转换为数字
SELECT inft.port FROM interfaces AS intf ORDER BY SUBSTRING(intf.port, LOCATE('/', intf.port)+1, LENGTH(intf.port)) + 0
#1
7
Try this:
SELECT port
FROM interfaces
ORDER BY SUBSTRING_INDEX(port, '/', 1), CAST(SUBSTRING_INDEX(port, '/', -1) AS SIGNED)
Check the SQL FIDDLE DEMO
检查SQL FIDDLE DEMO
OUTPUT
| PORT |
|--------|
| Fa0/1 |
| Fa0/2 |
| Fa0/3 |
| Fa0/4 |
| Fa0/5 |
| Fa0/6 |
| Fa0/7 |
| Fa0/8 |
| Fa0/9 |
| Fa0/10 |
| Fa0/11 |
| Fa0/12 |
| Gi0/1 |
| Gi0/2 |
| Null0 |
| Vlan1 |
#2
6
Why you need + 0
?? Simply remove it and it will work.
为什么你需要+ 0?只需将其移除即可。
SELECT port FROM interfaces ORDER BY RIGHT(port, 2)
SQL小提琴演示
Output:
PORT
------------
Fa0/1
Gi0/1
Gi0/2
Fa0/2
Fa0/3
Fa0/4
Fa0/5
Fa0/6
Fa0/7
Fa0/8
Fa0/9
Fa0/10
Fa0/11
Fa0/12
Null0
Vlan1
#3
1
The order is correct - lexicographically.
订单是正确的 - 按字典顺序排列。
You need to convert them to a number.
您需要将它们转换为数字。
#4
0
UPDATED
You need to do + 0
after extracting last two chars to convert it into number
在提取最后两个字符后,您需要执行+ 0将其转换为数字
SELECT inft.port FROM interfaces AS intf ORDER BY SUBSTRING(intf.port, LOCATE('/', intf.port)+1, LENGTH(intf.port)) + 0