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)
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 , !
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 .
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.
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.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With