I am trying to condense the below query which could have unlimited options based on a web form field. Users can input as many title keywords separated by commas. So my query would be constructed like the below with unlimited arguments:
"SELECT title FROM titles WHERE
title LIKE '%blue%'
AND
title like '%red%'
AND
title like '%green%'
AND
title like '%yellow%'
...";
Looking at this link, MySQL LIKE IN()?, it shows a good example of using regular expression, but it is using “OR”.
SELECT * from fiberbox where field REGEXP '1740|1938|1940';
What is the equivalent of using “AND”? For example, in quasi-SQL:
SELECT * from titles WHERE title REGEXP 'blue && red && green && yellow';
AND is a bit more difficult to do with regexes, and it doesn’t seem to be possible with MySQL’s limited regular expression syntax. If you are using the myISAM engine or MySQL 5.6, you can use the MATCH() function to get most of what you want:
However, I would recommend sticking to your simple chaining of ANDs. It’s less fragile, more powerful, and easier to code.