如何在MySQL中运行查询,以搜索多次出现的包含一个字符的字符串?
SELECT * FROM animals WHERE name LIKE '%r%'将只返回包含‘r’的动物。
+---------+------------+
| id | name |
+---------+------------+
| 1 | zebra |
| 14 | raccoon |
| 25 | parrot |
| 49 | rhinoceros |
+---------+------------+SELECT * FROM animals WHERE name LIKE '%rr%'将只返回包含“rr”实例的动物..
+---------+------------+
| id | name |
+---------+------------+
| 25 | parrot |
+---------+------------+我想找出任何包含“r”的动物名字..让我们在名字中的任何地方说两次。
+---------+------------+
| id | name |
+---------+------------+
| 25 | parrot |
| 49 | rhinoceros |
+---------+------------+有没有人?
发布于 2013-06-24 04:18:28
你试过这个吗?
select *
from animals
where name like '%r%r%'另一种解决方案是使用length并替换:
select *
from animals
where length(name) - length(replace(name, 'r', '')) >= 2;如果您正在查找一组字母的匹配项,例如'r'和's‘,这将非常有用:
select *
from animals
where length(name) - length(replace(replace(name, 'r', ''), 's', '')) >= 2;编辑:
如果你只想要两个“r”,你可以在where子句中使用相等:
select *
from animals
where length(name) - length(replace(name, 'r', '')) = 2;发布于 2013-06-24 04:19:55
您可以通过检查当您删除这些字符时字符串的长度有多大变化来间接地执行此操作:
SELECT id, name
FROM yourtable
WHERE (length(name) - length(replace(name, 'r', ''))) >= 2例如,parrot有6个字符,删除r后,只有4个字符,因此6-4=2,将匹配where。
https://stackoverflow.com/questions/17264899
复制相似问题