我使用 MySql 正则表达式:
SELECT * FROM myTable
WHERE title REGEXP "dog|cat|mouse";
数据集很小,所以我不关心性能。我更喜欢这个而不是 LIKE 表示法,因为我不必连接一堆“LIKE”语句。
但是,上述表示法使用逻辑 OR 运算符。是否有逻辑 AND 运算符,以便仅匹配包含所有关键字的行?
(我使用的是 InnoDB,所以全文搜索不是一个选项)
除了连接 AND 之外,真的没有很好的解决方案:
SELECT * FROM myTable
WHERE title REGEXP "dog"
AND title REGEXP "cat"
AND title REGEXP "mouse"
否则,正则表达式将如下所示:
SELECT * FROM myTable
WHERE title REGEXP "(dog.*cat.*mouse)|(dog.*mouse.*cat)|(mouse.*dog.*cat)|(mouse.*cat.*dog)|(cat.*dog.*mouse)|(cat.*mouse.*dog)"
AND
操作可能只能由 mysql-AND 访问:
WHERE title REGEXP 'dog' AND title REGEXP 'cat' AND title REGEXP 'mouse'
这只会显示所有关键字都在标题字段中的条目。像
title = "this is about mouse, cat and dog"
您可以在它们之间添加几个条件AND
:
SELECT * FROM myTable
WHERE title REGEXP "dog" AND title REGEXP "cat" AND title REGEXP "mouse";
也许这里不需要 REGEXP,您可以使用INSTR代替(常规通常较慢):
SELECT * FROM myTable
WHERE INSTR(title, "dog") AND INSTR(title, "cat") AND INSTR(title, "mouse");
您可以在布尔模式下使用全文搜索:
SELECT * FROM table WHERE MATCH(colmun_name) AGAINST('+dogs +cat' IN BOOLEAN MODE);
您必须首先索引您的表:
ALTER TABLE table ADD FULLTEXT(column_name);
如果您的标题包含所有搜索词,例如:
Anything mouse anything cat anything dog anything
然后,您将以任意顺序(例如 dog、cat 和 mouse)在重复 3 次的标题中获得所有搜索词。
Anything mouse anything cat anything DOG anything
Anything mouse anything CAT anything dog anything
Anything MOUSE anything cat anything dog anything
因此,您可以在不连接 AND 的情况下执行此操作:
SELECT * FROM myTable WHERE REPEAT(title,3) RLIKE '.*dog.*cat.*mouse.*';