使用以下查询
SELECT * FROM words WHERE word REGEXP '(ord)'
ford
,lord
,word
如何在这些字母出现但不包含相同顺序的字词中加入?
adore
,door
,random
修改:
有这个工作。
SELECT word, (
IF(LOCATE('o', word) > 0, 1, 0) +
IF(LOCATE('r', word) > 0, 1, 0) +
IF(LOCATE('z', word) > 0, 1, 0) +
IF(LOCATE('a', word) > 0, 1, 0) +
IF(LOCATE('d', word) > 0, 1, 0)) AS chars_present
from words
HAVING chars_present = 5
现在我如何查询包含字母r
两次的单词?
答案 0 :(得分:2)
在mysql中使用正则表达式要求所有三个字符都出现在任何位置都是丑陋的,并且你可能会更喜欢这样的东西:
SELECT (
IF(LOCATE('o', words) > 0, 1, 0) +
IF(LOCATE('r', words) > 0, 1, 0) +
IF(LOCATE('d', words) > 0, 1, 0)) AS chars_present
...
HAVING chars_present = 3
答案 1 :(得分:1)
只需重复每个字母的规则。
SELECT * FROM words WHERE word REGEXP 'o' AND word REGEXP 'r' AND word REGEXP 'd'
规则出现的顺序无关紧要。
答案 2 :(得分:1)
这可能是最快的:
SELECT *
FROM words
WHERE LOCATE('o', word)
AND LOCATE('r', word)
AND LOCATE('d', word);
mysql> SELECT city, state FROM us
WHERE locate('o', city) AND locate('r', city) AND locate('d', city)
LIMIT 11;
+---------------+-------+
| city | state |
+---------------+-------+
| Irondale | AL |
| Oxford | AL |
| El Dorado | AR |
| Paragould | AR |
| Sherwood | AR |
| Goodyear | AZ |
| Safford | AZ |
| Alondra Park | CA |
| Anderson | CA |
| Arroyo Grande | CA |
| Atascadero | CA |
+---------------+-------+
11 rows in set (0.00 sec)
如果您需要两个r
,那么对它们的测试将是word REGEXP 'r.*r'
:
mysql> SELECT city, state FROM us
-> WHERE locate('o', city) AND city REGEXP 'r.*r' AND locate('d', city)
-> LIMIT 5;
+--------------------+-------+
| city | state |
+--------------------+-------+
| Alondra Park | CA |
| Arroyo Grande | CA |
| Corte Madera | CA |
| Desert Hot Springs | CA |
| Garden Grove | CA |
+--------------------+-------+