Search code examples
mysqlsqlselectgroup-concatfind-in-set

MySQL: creating comma separated list and using in IN


My function code is like following.

DECLARE ids VARCHAR(55);
SELECT  GROUP_CONCAT(id) INTO ids 
        FROM tableName WHERE ...;
SELECT CONCAT(GROUP_CONCAT(id), ids ) INTO ids FROM tableName .....;
SELECT column_name FROM tableName WHERE id IN (**ids**);

In this i am creating id list with two select statement and applying into IN list. Its giving me null result . if i CAST the ids in like CONCAT(GROUP_CONCAT(id), CAST(ids as char) ) then its giving me first row result.


Solution

  • I have solved the problem by the following code

    DECLARE ids VARCHAR(55);
    SELECT GROUP_CONCAT(id SEPARATOR ',') INTO ids  FROM tableName WHERE ...;
    SELECT CONCAT_WS(',', CAST(GROUP_CONCAT(id SEPARATOR ',')AS CHAR), CAST(ids AS CHAR)) INTO ids FROM tableName .....;
    SELECT column_name FROM tableName WHERE FIND_IN_SET (id, ids );