在按其他字段排序时以数字方式对varchar进行排序

时间:2017-05-08 16:02:41

标签: mysql sorting casting

我需要按varchar对查询结果进行排序,其中可能包含数字,但也需要事先按其他字段排序。

说我的表看起来像:

+------------------------+-----------------+
| AnotherField           | VarCharWithNums |
+------------------------+-----------------|
| Same Data in Every Row | Numbers 5-10    |
| Same Data in Every Row | Numbers 10-13   |
| Same Data in Every Row | Numbers 13-15   |
+------------------------+-----------------|

此查询:

SELECT VarCharWithNums, AnotherField
FROM MyTable
ORDER BY CAST(VarCharWithNums AS UNSIGNED) ASC

给我这个:

+------------------------+-----------------+
| AnotherField           | VarCharWithNums |
+------------------------+-----------------|
| Same Data in Every Row | Numbers 5-10    |
| Same Data in Every Row | Numbers 10-13   |
| Same Data in Every Row | Numbers 13-15   |
+------------------------+-----------------|

此查询:

SELECT VarCharWithNums, AnotherField
FROM MyTable
ORDER BY AnotherField ASC, CAST(VarCharWithNums AS UNSIGNED) ASC

给我这个:

+------------------------+-----------------+
| AnotherField           | VarCharWithNums |
+------------------------+-----------------|
| Same Data in Every Row | Numbers 10-13   |
| Same Data in Every Row | Numbers 5-10    |
| Same Data in Every Row | Numbers 13-15   |
+------------------------+-----------------|

我在ORDER BY子句中给出字段的优先级并不重要,当我将其与其他字段一起订购时,它永远不会正确排序VarCharWithNums

1 个答案:

答案 0 :(得分:0)

你在上一段中提到过它,但是你所展示的唯一错误就是,为了得到你所描述的那种,CAST(VarCharWithNums AS UNSIGNED) ASC需要成为第一个的东西在ORDER BY子句中。它应该可以工作,当我在我的机器上创建一个人为的例子时它就可以工作。