简体   繁体   中英

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.

Try this:

DECLARE ids VARCHAR(55);
SELECT GROUP_CONCAT(id) INTO ids 
FROM (SELECT id 
      FROM tableName 
      WHERE...
      UNION 
      SELECT id 
      FROM tableName
      WHERE....
) AS A;

SELECT column_name FROM tableName WHERE FIND_IN_SET(id, ids);

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

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