I'm having some difficulty trying to figure out how to write a certain query.

The very basics are that I have two relevant tables: `containers` and `items`.
`containers` have the fields: ContainerID, ContainerName, and ContentType.
`items` have the fields: ItemID, ItemName, and ContainerID.

The easy part of the query is to return a result with the following fields:
ContainerName, ContentType, and GROUP_CONCAT(ItemName) to show all the Items in a container in one field, separated by commas or some other separator.

The problem comes in next. I need something such as a WHERE clause and/or a nested query or something that will return all containers that contain the item 'Apple' (or whatever item is specified in the where clause). The GROUP_CONCAT(Itemname) column must not just display 'Apple', it must still display all the items in that container, separated by a comma or some other separating charater.

I have tried different ideas but to no avail.

Any help will be appreciated.

PS. I'm using MySQL with PHP. So PHP suggestions are also welcome.

Re: Need help with a group_concat query 80 80


From what I see in the documentation you can treat the GROUP_CONCAT(itemname) as a list to test against.

select ContainerName, ContentType, and GROUP_CONCAT(ItemName) as itemnamelist
where "Apple" in GROUP_CONCAT(ItemName)
group by ContainerName

At least that is the way I read it. I would like to know if it works...

Re: Need help with a group_concat query 80 80

I think you need to change line 2 in the above query to:


You can also use the where clause in the following manner (in your query):

WHERE ContainerID IN (SELECT ContainerID FROM items WHERE ItemName = 'Apple')
Re: Need help with a group_concat query 80 80

Thanx for the help guys! Your replies got me searching in the right direction.
I found the sollution:

SELECT ContainerID, ContainerName, ContentType, GROUP_CONCAT(ItemName)
FROM container, item
WHERE container.ContainerID = item.ContainerID
HAVING GROUP_CONCAT(ItemName) like '%Apple%'
GROUP BY ContainerID
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.