简体   繁体   中英

Mysql GROUP_CONCAT using a GROUP_CONCAT in the query's IN()

I have a query:

SELECT GROUP_CONCAT(stores.store_name)
FROM stores
WHERE stores.id IN
(

  SELECT
  GROUP_CONCAT(users_x_stores.store_id) as stores_list
  FROM users_x_stores
  WHERE users_x_stores.user_id = 4

 );

The subquery, when run alone, returns a group_concat of 3 results - 14,4,8.

There are corresponding rows for the IDs 14,4,8 - but the overall query only returns one store name.

If I change the subquery to simply 14,4,8 the overall query works and a concatenation of 3 store names is returned.

Can anyone tell me what I am doing incorrectly here?

Thanks.

Avoiding doing an IN on a sub query, you can probably use a JOIN.

Assuming that users_x_stores.store_id contains a single store id for that user (with another row on users_x_stores for a different store for the same user):-

SELECT GROUP_CONCAT(stores.store_name)
FROM stores
INNER JOIN users_x_stores
ON stores.id = users_x_stores.store_id
WHERE users_x_stores.user_id = 4

If sers_x_stores.store_id is a comma separated list of stores (not a good table design, and probably not what you have done, but not clear from your original post) then you could do this

SELECT GROUP_CONCAT(stores.store_name)
FROM stores
INNER JOIN users_x_stores
ON FIND_IN_SET(stores.id, users_x_stores.store_id)
WHERE users_x_stores.user_id = 4

Try this

SELECT GROUP_CONCAT(stores.store_name)
FROM stores
WHERE stores.id IN
(
SELECT
users_x_stores.store_id as stores_list
FROM users_x_stores
WHERE users_x_stores.user_id = 4
); 

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