2

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.

4
  • your output is based on what exactly? why rows 3 and 4 not shown that had 6? Commented Sep 5, 2013 at 6:29
  • You'll find single value for ex: contains id 5, something like that? Commented Sep 5, 2013 at 6:29
  • @Akam Based on the first line of the question, I guess the "checking" value was "1,2,3", which would return rows with the id of 1, 2 and 3 as these rows also have a 1, 2 or 3 in the favourite_id col. Commented Sep 5, 2013 at 6:31
  • @Akam I have variable which have value '1,2,3' in it so any one of of it should be there in favourite_id Commented Sep 5, 2013 at 6:32

2 Answers 2

7

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

Comments

4

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

3 Comments

FIND_IN_SET will compare whole string and not each value in first operand so in my case if I compare '1,2,3' then output will be 0 result
then get all the results from the table, explode fav_ids and query them one by one with loop, but that is not a good approach.
there is thousands of records in table so it is not suitable to select and loop over result and then compare

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.