1

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?

Tom
  • 12,776
  • 48
  • 145
  • 240

1 Answers1

3

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.

CAUTION!!!!!

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

NOTE:

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

QUERY:

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.

OUTPUT:

'whatever,maybe,final'

now lets run the find in set query with the user defined variable and then again with just the string.

QUERY:

SELECT * 
FROM test 
WHERE FIND_IN_SET(words, @word_list );

OUTPUT:

+----+----------+
| id | words    |
+----+----------+
| 1  | whatever |
| 3  | maybe    |
| 4  | final    |
+----+----------+

WRITING IT IN:

SELECT * 
FROM test 
WHERE FIND_IN_SET(words, 'whatever,maybe,final')

OUTPUT:

+----+----------+
| id | words    |
+----+----------+
| 1  | whatever |
| 3  | maybe    |
| 4  | final    |
+----+----------+
Community
  • 1
  • 1
John Ruddell
  • 25,283
  • 6
  • 57
  • 86