M.S. M.S. - 2 months ago 11
MySQL Question

Filter records using a comma separated string

I've a string variable

@IDS
and I'm trying to filter the records from table
user
but nothing helping me out since I'm new to MySql.

SET @IDS = '1,2,3';
select * from user where find_in_set(@IDS,ID);

Answer

You need to switch the order of the parameters:

SELECT *
FROM user
WHERE FIND_IN_SET(ID, @IDS);

From the documentation:

FIND_IN_SET(str,strlist)
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings

In other words, the first parameter is the string you are trying to find in the CSV list of strings which is the second parameter. If ID can be found in @IDS, then the index (beginning at one) which matches will be returned. If no match be found, then zero will be returned.