I have the query below (shorted up all the fields in the select to just *’s).
SELECT u.*, e1.*, e2.*
FROM employee_db e1
JOIN employee_db e2 ON e1.manager_id = e2.id
JOIN users u ON u.id = e1.id
There are two more tables involved:
-
teams (need a flattened version of ‘team_name’ where user is assigned
to the team) -
team_user_associations (team_id, user_id)
(users have many teams through team_user_associations).
What I need is 1 field added to the results that’s a comma separated string of all the ‘team_name'(s) a users belongs to. I’m having trouble figuring out what the approach would be here… Would it be something like the resutls of a subquery where the ‘team_name’ field in the subqueries record set are flattend down to a comma separated string that becomes a field in the main query?
Thanks for any help!
You could try a solution like the one below:
Try it and tell me if it works, it’s difficult without knowing the structure and purpose of the other tables.
Anyway, the trick is to expand the rows by joining with team/user associations, and reducing them again with the GROUP BY. Having the associations now aggregated, you can use GROUP_CONCAT to retrieve the team name column.