Hardeep Pandya
Hardeep Pandya

Reputation: 917

compare two comma separated values in mysql

I have a variable which contains comma separated value '1,2,3'

and my table is as below

id    favourite_id
1     2,5,6
2     3,5,7
3     6,1,3
4     5,6,7

I want to check my variable against favourite_id column to find at least one value is common in favourite_id. so I want output of mysql query as below

id    favourite_id
1     2,5,6
2     3,5,7
3     6,1,3

I know that this is not normalized table structure but I am not able to change my database structure.I have googled a lot but could not found suitable solution.

Upvotes: 2

Views: 4664

Answers (2)

Hardeep Pandya
Hardeep Pandya

Reputation: 917

Found two solution with the use of REGEXP of mysql

(1)

`favourite_id` REGEXP '[[:<:]]1[[:>:]]|[[:<:]]2[[:>:]]|[[:<:]]3[[:>:]]' //faster then below

(2)

`favourite_id` REGEXP '(^|,)(1|2|3)(,|$)' //slower then above

Upvotes: 7

Muhammad
Muhammad

Reputation: 3250

use FIND_IN_SET(str,strlist)

More detail: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

SELECT FIND_IN_SET('b','a,b,c,d');

Upvotes: 4

Related Questions