gpt4 book ai didi

mysql - 如何多次查询包含一个字母的字符串?

转载 作者:可可西里 更新时间:2023-11-01 07:46:55 25 4
gpt4 key购买 nike

如何在 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 |
+---------+------------+

有人吗?

最佳答案

你试过吗?

select *
from animals
where name like '%r%r%'

另一种解决方案是使用长度并替换:

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;

关于mysql - 如何多次查询包含一个字母的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17264899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com