简体   繁体   中英

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.

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

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

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