I’m sorry for the incomplete title – I need a point in the right direction on this one too.
I’m trying to write a query for searching records that contain strings in a comma separated text field. I use MySql and php.
Records example:
recordID | statuses[TEXT]
1010 | 102
1011 | 100,103
1012 | 100,106,201,300
I query statues that I want to search for from another table statues_dataset
statusName | statusCode | Yes/No
name1 | 100 |
name2 | 101 |
name3 | 102 | Yes
name3 | 103 |
name4 | 106 | Yes
Now I would like to find all records that contain statues 102 OR 106
I can solve this in two steps
query statues_dataset for ones I want and then concat the condition part so I basically get the next query:
SELECT * FROM table AS t
WHERE t.statuses LIKE '%201%'
OR t.statuses LIKE '%206%'
OR this one
SELECT * FROM table AS t
WHERE FIND_IN_SET('201',t.statuses)
OR FIND_IN_SET('206',t.statuses)
I would get the result I want:
recordID | statuses
1010 | 102
1012 | 100,106,201,300
Now I was wondering if there is a better way to solve this. Preferably in one query.
Or in two queries where i would create a list of values I want to searh for.
I looked at FIND_IN_SET(str,strlist) function, but the problem is I need multiple str.
Is there a function I can use so I can fill it with multiple values I want to search for?
I’ve been googling but I’m afraid I don’t know how to properly ask.
I just read your post again, and you say “or” not “and”. The following query finds the records you are looking for:
I changed the like to include commas before and after the statuses string. This allows the query to search for “,105,” instead of “105”, to prevent matching “1050” and so on.
If you change your mind and want records that have all the statuses, then the query is a little more complicated. Here, the subquery matches first finds all records with any match on the codes. It then counts the number of matches and returns the records that match all individual codes.
Using of count distinct instead of count(*) just handles duplicates in the statuses table.