0
我需要排序查詢的結果由varchar
可能包含數字,但也可以事先排序其他字段。排序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
當我爲了它與其他領域。
http://stackoverflow.com/questions/5417381/mysql-sort-string-number –
您可能需要解析出該字段以獲取只有一個數字,並使用它進行排序(或兩個,取決於你如何想要對範圍進行排序) –
如果'AnotherField'的每一行都有相同的數據,爲什麼要對它進行排序?或者這只是人爲的例子的一部分?當我設置測試用例並嘗試時,我沒有任何問題。 –