【问题标题】:Sorting varchar column as numeric in mysql with null value as the bottom在mysql中将varchar列排序为数字,空值作为底部
【发布时间】:2013-08-06 07:45:34
【问题描述】:

我正在尝试对 mysql 查询中的列进行排序,该列的类型为 varchar,但可能/可能没有数值。

for example it may have the values

2012-10
2012-41
2012-1

which should be sorted as follows:
2012-1
2012-10
2012-41

but if the values are :
M-1
M-13
M-5

it should be sorted as :
M-1
M-5
M-13

and if null values are present it should be last.

不知道有没有可能。请帮忙

【问题讨论】:

  • 您只想按连字符后的数字进行数字排序?
  • no.. 就像在第一种类型中,也可以有值 2013-12,它也可以在 2012 值之后出现

标签: mysql sorting numeric varchar


【解决方案1】:

如果您想按连字符后的数字进行数字排序,请使用:

ORDER BY column IS NOT NULL, SUBSTRING_INDEX(column, '-', 1), CAST(SUBSTRING_INDEX(column, '-', 2) AS DECIMAL)

column IS NOT NULL 最后对空列进行排序,CAST() 表达式按数字对其余列进行排序。

【讨论】:

  • 感谢您的回复.. bt 我还需要将其与第一部分进行排序.. 我认为这在这种情况下不会起作用。
  • 我还添加了另一个子句以按连字符之前的部分排序。你没有在问题中这么说。
猜你喜欢
  • 2014-11-22
  • 2014-11-28
  • 2012-07-28
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多