如何编写MySQL SELECT查询以在数据库中查找只包含特定字符的单词?

huangapple go评论51阅读模式
英文:

How can I write a MySQL SELECT query to find words with only and only specific characters in database?

问题

Here are the translations of the code parts:

SELECT * FROM `WORDS_table` WHERE `word` LIKE '%a%' AND `word` LIKE '%b%';
NOTE: I continue to use php language to process the query result.

If you have any more code parts to translate, please provide them, and I'll be happy to assist.

英文:

I want to write a SELECT query in MySQL to find words with only and only specific characters in database.
For example if data is :

id  word
---------
1    a
2    b
3    aa
4    ab
5    aaa
6    aba
7    abc
8    abcd
9    abac
10   abaca

The query result to find 'a' and 'b' should be :

a
b
ab 

And the query result to find 'a' and 'b' and 'a' (Repeat 'a' twice) should be :

a
b
aa
ab
aba

And the query result to find 'a' and 'b' and 'a' and 'a' (Repeat 'a' three times) should be :

a
b
aa
ab
aaa
aba

Any idea ?

SELECT * FROM `WORDS_table` WHERE `word` LIKE '%a%' AND `word` LIKE '%b%'

is not correct, because it returns all the words with any of selected characters.

NOTE : I continue to use php language to process the query result.

答案1

得分: 1

你可以使用正则表达式:

select * from words where word rlike '^[ab]+$'

正则表达式解释:

  • ^ 字符串的开头
  • [ab]+ 匹配一个或多个字符 'a' 或 'b'
  • $ 字符串的结尾

fiddle:

select * 
from ( values row('a'), row('ab'), row('abc'), row('abcd') ) w(word)
where word rlike '^[ab]+$'
word
a
ab
英文:

You could use a regex:

select * from words where word rlike '^[ab]+$'

Regexp breakdown:

^       beginning of the string
[ab]+   1 to N occurrences of character 'a' or 'b' 
$       end of the string

fiddle:

select * 
from ( values row('a'), row('ab'), row('abc'), row('abcd') ) w(word)
where word rlike '^[ab]+$'

word
a
ab

huangapple
  • 本文由 发表于 2023年5月25日 03:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定