MySQL ORDER BY 删除非数字字符

MySQL ORDER BY remove non numeric characters

我有一个旧数据库,其中一些值是这样插入的:

blablabla2008
blablabla2010
blablabla2011

...其他一些(最新的)值作为数字插入:

2013
2014

有没有办法在 sql 查询中对其进行排序?

如果您关心的数字是最后四个字符(如您的示例所示),那么这很简单:

order by right(col, 4)

否则,问题会更难,因为 MySQL 没有提供查找或使用字符 类 的方法。一种方法是这样的:

order by (case when substring(col, -2, 1) not between '0' and '9'
               then right(col, 1) + 0
               when substring(col, -3, 1) not between '0' and '9'
               then right(col, 2) + 0
               when substring(col, -4, 1) not between '0' and '9'
               then right(col, 3) + 0
               when substring(col, -5, 1) not between '0' and '9'
               then right(col, 4) + 0
               . . .
          end)

即检查每个位置是否有非数字字符。