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?

2
  • have you looked at find_in_set? what does $search_term contain? Commented Aug 21, 2014 at 15:18
  • 2
    Why not use several regexp or instr conditions combined by OR? Commented Aug 21, 2014 at 15:19

1 Answer 1

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    |
+----+----------+
Sign up to request clarification or add additional context in comments.

2 Comments

Very nice, didn't know about it +1
@Fede thanks! I re-wrote a ton of my SQL queries when I came across this :) it's very useful! (especially when used with group_concat() )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.