Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL find_in_set with multiple search string

Tags:

search

mysql

I find that find_in_set only search by a single string :-

find_in_set('a', 'a,b,c,d') 

In the above example, 'a' is the only string used for search.

Is there any way to use find_in_set kind of functionality and search by multiple strings, like :-

find_in_set('a,b,c', 'a,b,c,d') 

In the above example, I want to search by three strings 'a,b,c'.

One way I see is using OR

find_in_set('a', 'a,b,c,d') OR find_in_set('b', 'a,b,c,d') OR find_in_set('b', 'a,b,c,d') 

Is there any other way than this?

like image 497
Mukesh Chapagain Avatar asked Feb 16 '11 10:02

Mukesh Chapagain


People also ask

How do I select multiple items in MySQL?

To select multiple values, you can use where clause with OR and IN operator.

What is Find_in_set in MySQL?

The FIND_IN_SET() function returns the position of a string within a list of strings.

How do I find Comma Separated Values in MySQL?

MySQL has an inbuilt function called FIND_IN_SET which will search for values within a comma separated values. It basically returns the index position of the first parameter within the second parameter. This can be alternatively used to replace the IN clause. WHERE FIND_IN_SET (item_description,'Mobile,laptop');


2 Answers

there is no native function to do it, but you can achieve your aim using following trick

WHERE CONCAT(",", `setcolumn`, ",") REGEXP ",(val1|val2|val3)," 
like image 192
Pavel Perminov Avatar answered Sep 23 '22 13:09

Pavel Perminov


The MySQL function find_in_set() can search only for one string in a set of strings.

The first argument is a string, so there is no way to make it parse your comma separated string into strings (you can't use commas in SET elements at all!). The second argument is a SET, which in turn is represented by a comma separated string hence your wish to find_in_set('a,b,c', 'a,b,c,d') which works fine, but it surely can't find a string 'a,b,c' in any SET by definition - it contains commas.

like image 28
Dmitry Avtonomov Avatar answered Sep 22 '22 13:09

Dmitry Avtonomov