英文:
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'$
字符串的结尾
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
select *
from ( values row('a'), row('ab'), row('abc'), row('abcd') ) w(word)
where word rlike '^[ab]+$'
word |
---|
a |
ab |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论