我需要按照可能包含数字的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与其他字段一起排序时,它永远不会正确排序。
发布于 2017-05-09 00:15:49
您在最后一段中提到了这一点,但是您所展示的内容中唯一的错误是,为了获得您所描述的排序,CAST(VarCharWithNums AS UNSIGNED) ASC必须是ORDER BY子句中的第一个内容。它应该可以工作,当我在我的机器上创建一个人为的例子时,它就可以工作了。
https://stackoverflow.com/questions/43852277
复制相似问题