I got three tables
objects id, field1, field2, ...
groups id, title, color
group_ref oid, gid
So every object can be in n groups.
I want to show a list of objects and one field of that list are the groups an object is in. So here is what i came up with:
SELECT o.id,
CONCAT_WS("||", GROUP_CONCAT(gx.gid separator "|"), GROUP_CONCAT(gr.title, "#", gr.color separator "|")) AS groups
FROM objects AS o
LEFT JOIN group_ref AS gx ON o.id = gx.oid
LEFT JOIN groups AS gr ON gx.gid = gr.id
WHERE 1
GROUP BY o.id
That actually works and i can create the needed interface out of the (concatenated) groups field.
Problem is: How to select objects who are in one specific group only (e.g. gid=4)?
This only gets a part of the results:
WHERE gr.id = 4
or
HAVING gr.id = 4
Any help greatly appreciated! (maybe there is a more elegant way for the concat thingy too)
If I understand you correctly, you want to get all objects in group 4 and all the groups those object are in. You want to JOIN on the group_ref table twice, once to filter (regular JOIN) and once to get the related groups (LEFT JOIN).