Order by last 2 characters string

丶灬走出姿态 提交于 2019-12-21 12:26:51

问题


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.

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: sqlfiddle


回答1:


Try this:

SELECT port 
FROM interfaces 
ORDER BY SUBSTRING_INDEX(port, '/', 1), CAST(SUBSTRING_INDEX(port, '/', -1) AS SIGNED)

Check the 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:


Why you need + 0 ?? Simply remove it and it will work.

SELECT port FROM interfaces ORDER BY RIGHT(port, 2)

SQL Fiddle Demo

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:


The order is correct - lexicographically.

You need to convert them to a number.




回答4:


UPDATED

You need to do + 0 after extracting last two chars to convert it into number

SELECT inft.port FROM interfaces AS intf ORDER BY SUBSTRING(intf.port, LOCATE('/', intf.port)+1, LENGTH(intf.port)) + 0


来源:https://stackoverflow.com/questions/20540656/order-by-last-2-characters-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!