I am working on a query that for now has worked well (I’m using input from frontend to generate the WHERE clause), but I want to be able to search on another parameter and this truly makes my mind boggle.
- Table
groupscontains id, name. - Table
personsis my table with the persons that I want to retrieve. - Table
group_membershipsis my group<->person many-to-many relationship table. The columns are participant (person.id) and group (groups.id)
The retrieved result set’s last column is a concatenation of group_memberships but where “1, 2, 3” has been replaced with the groups’ real names via JOIN.
Here’s the query today:
SELECT
`persons`.`id`,
CONCAT_WS(\' \', `fname`, `lname`) AS `full_name`,
`job_title`,
`email`,
`phone`,
`participant_group_memberships`.`memberships`
FROM
`persons`
LEFT JOIN (SELECT
`participant`, `name`,
GROUP_CONCAT(`groups`.`name` ORDER BY `groups`.`name`
SEPARATOR \', \') AS `memberships`
FROM
`group_memberships` JOIN `groups`
ON (`groups`.`id` = `group_memberships`.`group`)
GROUP BY `participant`) AS `participant_group_memberships`
ON (`participant_group_memberships`.`participant` = `persons`.`id`)
WHERE TRUE . $where . '
ORDER BY `full_name`
If I add WHERE name = ‘search_query_group’ then the concatenated list only will show that group which is not what I want. I still want to show all the groups that person belongs to.
I also want to achieve this with 1 query, and avoid having to use IN(), if possible.

As you can see, the last column (generated with GROUP_CONCAT) will only show the group I searched on, not all the groups the person is member of.
You could use a SUM and CASE statement in a HAVING clause in your subquery to include your search results. You would also need to change your join to the subquery to be an INNER JOIN. This will return all persons who are in a certain group and show all of the groups they are members of.