MySQL 你如何从mysql中选择字符串中的最后一个字符= x?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1270055/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:51:55  来源:igfitidea点击:

How do you select from mysql where last character in a string = x?

mysql

提问by Josh Davis

I'd like to select rows from the database where the last character in the mov_id column equals to 1 and 2.

我想从数据库中选择 mov_id 列中的最后一个字符等于 1 和 2 的行。

How would the query look like?

查询会是什么样子?

回答by nickf

SELECT * FROM `myTable` WHERE `mov_id` LIKE '%1' OR `mov_id` LIKE '%2'

the %character is a wildcard which matches anything (like *in many other places)

%字符是一个通配符,可以匹配任何内容(就像*在许多其他地方一样)

回答by Josh Davis

If mov_idis a numeric value (TINYINT, INT, etc...) then you should use a numeric operator. For instance, use the modulo operator to keep the last digit

如果mov_id是数字值(TINYINT、INT 等...),则应使用数字运算符。例如,使用模运算符保留最后一位数字

SELECT * FROM mytable
WHERE (mov_id MOD 10) IN (1, 2)

If mov_idis a string, you can use LIKE or SUBSTRING(). SUBSTRING() will be slightly faster.

如果mov_id是字符串,则可以使用 LIKE 或SUBSTRING()。SUBSTRING() 会稍微快一点。

SELECT * FROM mytable
WHERE SUBSTRING(mov_id, -1) IN ('1', '2')

If your table is big or that query is frequently run, you should definitely consider adding a column to your table, in which you would store mov_id's last digit/character, and index that column.

如果您的表很大或该查询经常运行,您绝对应该考虑在表中添加一列,您将在其中存储mov_id的最后一位数字/字符,并索引该列。

回答by Vijunav Vastivch

Try this way too:

也试试这个方法:

Select feild1 from table where right(feild1,1) = 'x'

it displays the fields that has last a value of x.

它显示最后一个值为 x 的字段。

回答by ajay verma

SELECT * FROM TABLE WHERE RIGHT(COLUMN_NAME,1) IN ('X')

SELECT * FROM TABLE WHERE RIGHT(COLUMN_NAME,1) IN ('X')

if you want to match two character just replace 1 by 2 .In general RIGHT(COLUMN_NAME,NO_OF_CHARACTER_YOU WANT_TO_MATCH_FROM_LAST)

如果您想匹配两个字符,只需将 1 替换为 2 。一般来说 RIGHT( COLUMN_NAME, NO_OF_CHARACTER_YOU WANT_TO_MATCH_FROM_LAST)

And if you want to match the starting char just use LEFT instead of RIGHT

如果你想匹配起始字符,只需使用LEFT 而不是 RIGHT

回答by Ravean

SELECT * FROM table WHERE mov_idREGEXP '1$' OR mov_idREGEXP '2$'

SELECT * FROM table WHERE mov_idREGEXP '1$' OR mov_idREGEXP '2$'

回答by Mr. Smith

You could also do something like:

您还可以执行以下操作:

select
     your, fields, go, here
from table
where
     substring(mov_id, (char_length(move_id) - 1)) = x