Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical AND operator in mySql REGEXP?

Tags:

regex

mysql

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)

like image 673
user1031947 Avatar asked Mar 28 '13 16:03

user1031947


People also ask

What are the logical operators in MySQL?

In SQL, all logical operators evaluate to TRUE , FALSE , or NULL ( UNKNOWN ). In MySQL, these are implemented as 1 ( TRUE ), 0 ( FALSE ), and NULL . Most of this is common to different SQL database servers, although some servers may return any nonzero value for TRUE . NOT , !

Can we use REGEXP in MySQL?

MySQL allows you to match pattern right in the SQL statements by using REGEXP operator. This statement performs a pattern match of a string_column against a pattern .

What does REGEXP do in MySQL?

MySQL REGEXP performs a pattern match of a string expression against a pattern. The pattern is supplied as an argument. If the pattern finds a match in the expression, the function returns 1, else it returns 0. If either expression or pattern is NULL, the function returns NULL.

What is the difference between the like and REGEXP operators in MySQL?

Basically, LIKE does very simple wildcard matches, and REGEX is capable of very complicated wildcard matches. In fact, regular expressions ( REGEX ) are so capable that they are [1] a whole study in themselves [2] an easy way to introduce very subtle bugs.


1 Answers

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)"
like image 184
m4573r Avatar answered Sep 22 '22 22:09

m4573r