在mysql中查找最后一个字母数字值

时间:2010-08-22 16:25:21

标签: sql mysql sql-order-by

我有一个包含mysql数据库中用户名的字段 例如:

johndoe2
johndoe10
johndoe3

如果我按该字段DESC订购,我会:

johndoe3
johndoe2
johndoe10

我需要得到:

johndoe10
johndoe3
johndoe2 

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

这是一个巨大的黑客,但我认为会奏效。如果您的列名是s:

order by 
  (replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(s, '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', ''),
  length(s) desc,
  s desc

首先按文本的字母部分排序,将所有相同的名称组合在一起,然后按长度对它们进行大致数字排序,然后按s进行排序。最后一个order by s现在正常工作,因为它仅用于消除具有相同位数的相同名称之间的歧义。

答案 1 :(得分:0)

如果不考虑性能,请考虑编写function like this one to remove non-numeric characters,然后只需将调用包含在您的ORDER BY中。

 SELECT * 
 FROM MyTable
 ORDER BY 
      CAST(strip_alpha(UserName) as int) DESC

对于更高性能+无障碍的解决方案,请考虑将用户名中的数字提取到新列中。然后你可以轻松订购:

 SELECT *
 FROM MyTable
 WHERE  UserName LIKE 'johndoe%'
 ORDER BY TrailingDigit DESC