在mysql varchar字段中对连字符分隔值进行排序

时间:2014-06-19 10:05:22

标签: mysql

如何在mysql varchar字段中对连字符分隔的数字进行排序。我在一个字段中有数字列表

700-657-1
700-657-10
700-657-2
700-657-3
700-657-4

1 个答案:

答案 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子句。

SQL Fiddle demo

修改

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