consider three entities as student, course, subject
Below are the associations –
student has_many courses,
student has_many subjects.
Now i want to fetch student records with subject names and course names using mysql group_concat, left join on courses, left join on subjects and group_by student_id.
Problem is that group_concat('subjects.name') as subject_names gives me duplicate entries of subjects but group_concat('students.name') as student_names gives unique names.
Why ??
The 2 left joins are multiplying rows via Cartesian product of the child rows per student
Example
coursevalue per subject = each course repeated twicesubjectvalue per course = each subject repeated thriceTo fix:
Option 1: Use
GROUP_CONCAT(DISTINCT ...)as per MySQL docsOption 2: Use a UNION ALL + derived table
The 2nd option may be better albeit more complex because you have less intermediate rows to process with DISTINCT