I have the following query which searches a column for a given string
SELECT * FROM table WHERE column_name REGEXP '$search_term'
Is it possible to search that column to see whether it contains one (or more) words from an array?
I have the following query which searches a column for a given string
SELECT * FROM table WHERE column_name REGEXP '$search_term'
Is it possible to search that column to see whether it contains one (or more) words from an array?
you can use FIND_IN_SET() to find one or more words
SELECT *
FROM table
WHERE FIND_IN_SET(column_name, 'word1,word2,word3')
what find in set does is it looks at the value inside a column and compares it to the values in your comma separated string.
don't put a variable directly in a query like that.. it makes you VULNERABLE to SQL INJECTION attacks!!!! you should look into using prepared statements.. look HERE for help with sql injection
if you dont have a way to get a comma separated list of words you can use GROUP_CONCAT().. I'll provide a demo below using both ways.
here is a SQLFIDDLE
SET @word_list := (SELECT GROUP_CONCAT(words) FROM test where id IN(1, 3, 4));
SELECT @word_list;
after assigning the string to @word_list you want to see whats in it so I select it.
'whatever,maybe,final'
now lets run the find in set query with the user defined variable and then again with just the string.
SELECT *
FROM test
WHERE FIND_IN_SET(words, @word_list );
+----+----------+
| id | words |
+----+----------+
| 1 | whatever |
| 3 | maybe |
| 4 | final |
+----+----------+
SELECT *
FROM test
WHERE FIND_IN_SET(words, 'whatever,maybe,final')
+----+----------+
| id | words |
+----+----------+
| 1 | whatever |
| 3 | maybe |
| 4 | final |
+----+----------+