[英]Find last alphanumeric value in mysql
我有一个字段,其中包含mysql db中的用户名,例如:
johndoe2
johndoe10
johndoe3
如果我通过该字段DESC
订购,我将得到:
johndoe3
johndoe2
johndoe10
我需要得到:
johndoe10
johndoe3
johndoe2
任何帮助表示赞赏
这是一个巨大的hack,但我认为可以。 如果您的列名是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
的最后一个order by s
现在可以正常工作,因为它仅用于区分具有相同位数的相同名称。
如果不关心性能,请考虑编写类似这样的函数以删除非数字字符 ,然后将调用简单地包含在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.