带有小数的MySQL订单

时间:2013-03-12 23:35:22

标签: mysql sql-order-by

我遇到了mysql排序的问题。 我的问题:

SELECT * FROM versions ORDER BY version DESC

它列出了一些像这样的版本:

25.0.1364.86
25.0.1364.124
23.0.1271.100

然而.124高于.86。

我该如何解决?

5 个答案:

答案 0 :(得分:3)

从@peterm发布的查询的一个小改进(谢谢!)

SELECT *
FROM `versions`
ORDER BY 1*SUBSTRING_INDEX(version, '.', 1) asc, 
     1*SUBSTRING_INDEX(SUBSTRING_INDEX(version, '.', -3),'.', 1) asc, 
     1*SUBSTRING_INDEX(SUBSTRING_INDEX(version, '.', -2),'.', 1) asc, 
     1*SUBSTRING_INDEX(version, '.', -1) asc,
     version asc # this will sort non-numeric strings

我测试了更复杂的值,字母,数字,短划线和点,因为版本可以用任何格式编写。

| version |
-----------
| a-b     |
| a-c     |
| ab      |
| b       |
| c       |
| c.a     |
| c.a.b   |
| c.b     |
| c.b.a   |
| c.b.b   |
| ca      |
| 1.2     |
| 1.2.1   |
| 2.1.1   |
| 2.1.2   |
| 3       |
| 10      |
| 123     |

答案 1 :(得分:2)

如果version列的格式已修复,则您可以将版本拆分为多个部分并ORDER BY

SELECT *
FROM versions
ORDER BY 1*SUBSTRING_INDEX(version, '.', 1) DESC, 
         1*SUBSTRING_INDEX(SUBSTRING_INDEX(version, '.', -3),'.', 1) DESC, 
         1*SUBSTRING_INDEX(SUBSTRING_INDEX(version, '.', -2),'.', 1) DESC, 
         1*SUBSTRING_INDEX(version, '.', -1) DESC

输出:

|       VERSION |
-----------------
| 25.0.1364.124 |
| 25.0.1364.86  |
| 23.0.1271.100 |

<强> SQLFiddle

答案 2 :(得分:0)

在不知道如何定义表versions的情况下,很难肯定回答,但看起来它正在被搜索为文本,在这种情况下86大于124(想想字典排序)。 一个简单的解决方案可能是在表中以两种格式存储数据 - 保留您似乎拥有的字符串,并具有十进制等效值,例如25.0.1364.86作为字符串,2501364.86作为小数。这将确保您的订购按预期工作。

答案 3 :(得分:0)

这是我的方法(希望你不介意我blogged about it):

SELECT v.version 
FROM   (SELECT version, 
               Cast(Substring_index(version, '.', 1) AS UNSIGNED INTEGER)  major, 
               Cast(Substring_index(Substring_index(version, '.' 
                   , 2 ), '.', -1) AS UNSIGNED INTEGER)                    minor, 
               Cast(Substring_index(Substring_index(version, '.' 
                   , -2 ), '.', 1) AS UNSIGNED INTEGER)                    patch, 
               Cast(Substring_index(version, '.', -1) AS UNSIGNED INTEGER) build 
        FROM   versions) v 
ORDER  BY v.major, 
          v.minor, 
          v.patch, 
          v.build

<强>结果

|       VERSION |
-----------------
| 23.0.1271.100 |
|  25.0.1364.86 |
| 25.0.1364.124 |

See the demo

答案 4 :(得分:0)

晚会,但使用INET_ATON()函数可以更轻松地解决这个问题。

SELECT * FROM versions ORDER BY INET_ATON(version)

将输出

23.0.1271.100
25.0.1364.86
25.0.1364.124

在此处阅读有关INET_ATON()的更多信息:http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton