Domanda

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.

È stato utile?

Soluzione 2

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top