按最后2个字符的顺序排序

时间:2013-12-12 10:16:39

标签: mysql sql select sql-order-by

这是我查询的结果,但它没有正确排序。我想按最后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

我的查询:

SELECT inft.port FROM interfaces AS intf ORDER BY RIGHT(intf.port + 0, 2)

第二:sqlfiddle

4 个答案:

答案 0 :(得分:7)

试试这个:

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

检查SQL FIDDLE DEMO

<强>输出

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

答案 1 :(得分:6)

为什么你需要+ 0?只需删除它就可以了。

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

SQL Fiddle Demo

输出:

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

答案 2 :(得分:1)

订单是正确的 - 按字典顺序排列。

您需要将它们转换为数字。

答案 3 :(得分:0)

<强>已更新

在提取最后两个字符后,您需要+ 0将其转换为数字

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