简体   繁体   中英

Search using comma separated string

So I think I completely misunderstood how FIND_IN_SET work

SELECT
    u.*, p.*
FROM
    users u
INNER JOIN profiles p ON p.user_id = u.id
WHERE
FIND_IN_SET('1,4,7', p.fruits)

This is not working as I thought it would.

1,4,7 represent the fruits selected by the user to search

p.fruits can look something like this 1,2,3,4,5,6,7 or 5,6,7 or 1,6,7 etc

Basically I want to find the records if any of the values in the first argument match any of the values in the second argument.

Is this possible?

if your p.fruits column is a varchar (which is not ideal for this situation, but if it is so) your query will be like

where …  ( concat(',', p.fruits , ‘,’) like ‘%,1,%’  
or concat(',', p.fruits , ‘,’) like ‘%,4,%’  or concat(',',p.fruits , ‘,’) like ‘%,7,%’ ) ... 

this won't be good for indexes since concatenation will disable usage of indexes .. better solution would be turn the column into a set and do the query like Michael's above .. or you can create a new table called user_fruits(fk_user_id int, fruit_id int) and create unique index on both fields and do the search in user_fruits table

Use FIELD instead of that.

FIELD(p.fruits, 1,4,7)

You should refer to this article:

10 things in MySQL (that won't work as expected)

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