Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query finding values in a comma separated string

I have a field COLORS (varchar(50)) in a my table SHIRTS that contains a comma delimited string such as 1,2,5,12,15,. Each number representing the available colors.

When running the query select * from shirts where colors like '%1%' to get all the red shirts (color=1), I also get the shirts whose color is grey (=12) and orange (=15).

How should I rewrite the query so that is selects ONLY the color 1 and not all colors containing the number 1?

like image 812
bikey77 Avatar asked Feb 17 '11 18:02

bikey77


People also ask

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');

How do you find comma separated values in SQL query?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

The classic way would be to add commas to the left and right:

select * from shirts where CONCAT(',', colors, ',') like '%,1,%' 

But find_in_set also works:

select * from shirts where find_in_set('1',colors) <> 0 
like image 177
Andomar Avatar answered Sep 24 '22 23:09

Andomar


FIND_IN_SET is your friend in this case

select * from shirts where FIND_IN_SET(1,colors)  
like image 39
Shakti Singh Avatar answered Sep 21 '22 23:09

Shakti Singh