Using GROUP_CONCAT on subquery in MySQL Using GROUP_CONCAT on subquery in MySQL mysql mysql

Using GROUP_CONCAT on subquery in MySQL


OP almost got it right. GROUP_CONCAT should be wrapping the columns in the subquery and not the complete subquery (I'm dismissing the separator because comma is the default):

SELECT i.*,(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlistFROM items iWHERE i.id = $someid

This will yield the desired result and also means that the accepted answer is partially wrong, because you can access outer scope variables in a subquery.


You can't access variables in the outer scope in such queries (can't use items.id there). You should rather try something like

SELECT    items.name,    items.color,    CONCAT(favourites.userid) as idlistFROM    itemsINNER JOIN favourites ON items.id = favourites.itemidWHERE    items.id = $someidGROUP BY    items.name,    items.color;

Expand the list of fields as needed (name, color...).


I think you may have the "userid = itemid" wrong, shouldn't it be like this:

SELECT ITEMS.id,GROUP_CONCAT(FAVOURITES.UserId) AS IdListFROM FAVOURITES INNER JOIN ITEMS ON (ITEMS.Id = FAVOURITES.ItemId OR FAVOURITES.UserId = ITEMS.Creator)WHERE ITEMS.Id = $someidGROUP BY ITEMS.ID