I am looking for some feedback regarding the best way to handle the following (simplified for this example) situation.
I have 3 tables: tasks, assignees, and users
---tasks----
id, task, completed
---assignees----
user_id, task_id
---users---
id, name
I need to select tasks with concatenated user names of assignees, like so
tasks.task | assigned_names.names
---------------------------------------
"My task" | "Joe Schmoe, Bob Mcbart, Sally McGuire"
Here is what I have currently
SELECT tasks.task, assigned_names.names
FROM tasks
LEFT JOIN (
SELECT
GROUP_CONCAT( users.name SEPARATOR ',' ) AS names,
assignees.task_id
FROM assignees
LEFT JOIN users ON users.id = assignees.user_id
GROUP BY assignees.task_id
) assigned_names ON assigned_names.task_id = tasks.id
WHERE tasks.completed IS NULL
My main concern is that the assignees table has hundreds of thousands of records, and doing a group on the whole table every time seems like not a good idea.
Is there a better strategy?
Also, I would be happy to rephrase my question title if someone could suggest better language.
Thanks!
Best Answer
Simplicity is beautify. Multiple
JOIN
s are allowed. There is no need to the JOINs to beLEFT JOINS
as you want data that maches always.