MySQL 按最后 3 个字符排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13732026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order by last 3 chars
提问by Justin Blair
I have a table like:
我有一张像:
id name
--------
1 clark_009
2 clark_012
3 johny_002
4 johny_010
I need to get results in this order:
我需要按以下顺序获得结果:
johny_002
clark_009
johny_010
clark_012
Do not ask me what I already tried, I have no idea how to do this.
不要问我已经尝试过什么,我不知道该怎么做。
回答by Steven Moseley
This will do it, very simply selecting the right-most 3 characters and ordering by that value ascending.
这将做到这一点,非常简单地选择最右边的 3 个字符并按该值升序排列。
SELECT *
FROM table_name
ORDER BY RIGHT(name, 3) ASC;
It should be added that as your data grows, this will become an inefficient solution. Eventually, you'll probably want to store the numeric appendix in a separate, indexed integer column, so that sorting will be optimally efficient.
应该补充的是,随着数据的增长,这将成为一种低效的解决方案。最终,您可能希望将数字附录存储在单独的索引整数列中,以便以最佳方式进行排序。
回答by Marcelo Biffara
you should try this.
你应该试试这个。
SELECT * FROM Table order by SUBSTRING(name, -3);
good luck!
祝你好运!
回答by amk
You may apply substring_index function to parse these values -
您可以应用 substring_index 函数来解析这些值 -
select * from table order by substring_index(name, '_', -1)
回答by Sumon Sarker
You can use MySQL SUBSTRING()
function to sort by substring
您可以使用 MySQLSUBSTRING()
函数按子字符串排序
Syntax :
SUBSTRING(string,position,length)
句法 :
SUBSTRING(string,position,length)
Example :Sort by last 3 characters of a String
示例:按字符串的最后 3 个字符排序
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, -3);
#OR
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, -3,3);
Example :Sort by first 3 characters of a String
示例:按字符串的前 3 个字符排序
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, 1,3);
Note :
Positive
Position/Index start from Left to Right andNegative
Position/Index start from Right to Left of the String.
注意:
Positive
位置/索引从Negative
字符串的左到右开始,位置/索引从字符串的右到左开始。
Here is the details about SUBSTRING()function.
这是有关SUBSTRING()函数的详细信息 。