MySQL 使用mysql查询获取字符串的最后5个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10134609/
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
Getting last 5 char of string with mysql query
提问by
I have to get last 5 numbers using mysql.
我必须使用 mysql 获取最后 5 个数字。
My values are like YOT-A78514
,LOP-C4521
...
我的价值观是YOT-A78514
,LOP-C4521
...
I have to get only last five char . How can I do this in query?
我只需要得到最后五个字符。我怎样才能在查询中做到这一点?
回答by
You can do this with RIGHT(str,len)function. Returns the rightmost lencharacters from the string str,
您可以使用RIGHT(str,len)函数执行此操作。返回字符串str 中最右边的len 个字符,
Like below:
像下面这样:
SELECT RIGHT(columnname,5) as yourvalue FROM tablename
回答by Juha Palom?ki
"Right"-function is the way to, using the substring may lead to an problem that is not so easy to notice:
"Right"-function 是一种方法,使用子字符串可能会导致一个不太容易注意到的问题:
mysql> select right('hello', 6);
+-------------------+
| right('hello', 6) |
+-------------------+
| hello |
+-------------------+
1 row in set (0.00 sec)
mysql> select substring('hello', -6);
+------------------------+
| substring('hello', -6) |
+------------------------+
| |
+------------------------+
1 row in set (0.00 sec)
But if you don't try to go past the start of the string, then substring of course works fine:
但是,如果您不尝试越过字符串的开头,那么子字符串当然可以正常工作:
mysql> select substring('hello', -5);
+------------------------+
| substring('hello', -5) |
+------------------------+
| hello |
+------------------------+
1 row in set (0.00 sec)
回答by Ankit Sharma
Right
is a good choice but you can also use substring
like this-
Right
是一个不错的选择,但您也可以substring
这样使用-
SELECT Substring(columnname,-5) as value FROM table_name
回答by sheasie
SELECT row_id
FROM column_name
WHERE column_value LIKE '%12345';
This will return the "row_id" when "12345" is found to be the tailing suffix of the "column_value" within the "column_name".
当发现“12345”是“column_name”中“column_value”的尾随后缀时,这将返回“row_id”。
回答by xtrm
And if you want to get a dinamic number of right characters after a character:
如果你想在一个字符后得到一个正确的字符数:
SELECT TRIM(
RIGHT(
database.table.field,
(LENGTH(database.table.field) - LOCATE('-',database.table.field))
)
)
FROM database.table;