简体   繁体   中英

MySQL regexp against an array of terms

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.

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    |
+----+----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM