Logical AND operator in mySql REGEXP?

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

I use MySql REGEXP:

SELECT * FROM myTable WHERE title REGEXP "dog|cat|mouse"; 

The dataset is small, so I am not concerned about performance. And I prefer this over LIKE notation, because I do not have to concatenate a bunch of "LIKE" statements.

However, the above notation uses a logical OR operator. Is there a logical AND operator, so that only rows containing all of the keywords are matched?

(I am using InnoDB so fulltext search not an option)

回答1:

There's really no nice solution except concatenating ANDs:

SELECT * FROM myTable WHERE title REGEXP "dog" AND title REGEXP "cat" AND title REGEXP "mouse" 

The regular expression would otherwise look like this:

SELECT * FROM myTable WHERE title REGEXP "(dog.*cat.*mouse)|(dog.*mouse.*cat)|(mouse.*dog.*cat)|(mouse.*cat.*dog)|(cat.*dog.*mouse)|(cat.*mouse.*dog)" 


回答2:

You can add several conditions with AND between them:

SELECT * FROM myTable WHERE title REGEXP "dog" AND title REGEXP "cat" AND title REGEXP "mouse"; 

Maybe REGEXP is not necessary here and you may use INSTR instead (regular are usually slower):

SELECT * FROM myTable WHERE INSTR(title, "dog") AND INSTR(title, "cat") AND INSTR(title, "mouse"); 


回答3:

AND operation may be only accessible by the mysql-AND:

WHERE title REGEXP 'dog' AND title REGEXP 'cat' AND title REGEXP 'mouse' 

this will only show those entries where all the keywords are in the title field. like

title = "this is about mouse, cat and dog" 


回答4:

You can use full text search in boolean mode:

SELECT * FROM table WHERE MATCH(colmun_name) AGAINST('+dogs +cat' IN BOOLEAN MODE); 

You must index your table first:

ALTER TABLE table ADD FULLTEXT(column_name); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!