如何在mysql varchar字段中对连字符分隔的数字进行排序。我在一个字段中有数字列表
700-657-1
700-657-10
700-657-2
700-657-3
700-657-4
答案 0 :(得分:1)
如果您总是有三部分(固定计数或您可以确定最大部件数量)值,那么您有两个选择:
如何执行第二个选项的示例:
SELECT
val,
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 1), LENGTH(SUBSTRING_INDEX(VAL, '-', 0)) + 1), '-', '') AS UNSIGNED ) AS first,
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 2), LENGTH(SUBSTRING_INDEX(VAL, '-', 1)) + 1), '-', '') AS UNSIGNED ) AS second,
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 3), LENGTH(SUBSTRING_INDEX(VAL, '-', 2)) + 1), '-', '') AS UNSIGNED ) AS third
FROM
test
ORDER BY
first ASC, second ASC, third ASC
如果您不想返回它们,可以将表达式移动到ORDER BY
子句。
修改强>
SELECT
val
FROM
test
ORDER BY
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 1), LENGTH(SUBSTRING_INDEX(val, '-', 0)) + 1), '-', '') AS UNSIGNED ) ASC,
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 2), LENGTH(SUBSTRING_INDEX(val, '-', 1)) + 1), '-', '') AS UNSIGNED ) ASC,
CAST(REPLACE(SUBSTRING(SUBSTRING_INDEX(val, '-', 3), LENGTH(SUBSTRING_INDEX(val, '-', 2)) + 1), '-', '') AS UNSIGNED ) ASC