我有一个名为tbl_sort的表,其中包含以下行:
+---------------+
| sort_alphanum |
+---------------+
| 1 |
| 1.1 |
| 1.10 |
| 1.2 |
| 10 |
| 2a |
| 3b |
+---------------+
我想将这些行排序为所谓的“自然排序”,如下所示:
+---------------+
| sort_alphanum |
+---------------+
| 1 |
| 1.1 |
| 1.2 |
| 1.10 |
| 2a |
| 3b |
| 10 |
+---------------+
我尝试过这种语法:
SELECT
tbl_sort.sort_alphanum
FROM
tbl_sort
ORDER BY CAST(sort_alphanum AS UNSIGNED), sort_alphanum
但上述结果如下:
+---------------+
| sort_alphanum |
+---------------+
| 1 |
| 1.1 |
| 1.10 |
| 1.2 |
| 2a |
| 3b |
| 10 |
+---------------+
正如你所看到的那样,1.10行应该放在1.2之后。如何像第一个例子那样实现结果?
答案 0 :(得分:1)
检查一下:
SELECT
tbl_sort.sort_alphanum
FROM
tbl_sort ORDER BY
CONVERT(sort_alphanum,DECIMAL(10,0)) asc,
CAST(SUBSTR(sort_alphanum FROM 3) AS UNSIGNED)
答案 1 :(得分:0)
尝试以下操作,它只会为您提供样本数据的预期结果,不确定它是否适用于实际数据,无论如何都要尝试。
SELECT
sort_alphanum
FROM tbl_sort
-- WHERE sort_alphanum IN ('1.1', '1.10', '1.2')
ORDER BY CASE WHEN LOCATE('.', sort_alphanum) THEN LEFT(sort_alphanum, LOCATE('.', sort_alphanum) - 1) ELSE sort_alphanum END + 0,
CASE WHEN LOCATE('.', sort_alphanum) THEN REPLACE(sort_alphanum, '.', '') END + 0