Search code examples
mysqlgroup-byleft-joingroup-concat

MySQL getting duplicates using multiple left join


For some reason I'm getting duplicate values from the Tags and Person table using following query:

# Selects
SELECT 
Organization.name AS 'Name',
GROUP_CONCAT(Person.name) AS 'Persons',
GROUP_CONCAT(Tag.name) AS 'Tags'

# From
FROM Organization

# Joins
LEFT JOIN Person ON Organization.id = Person.organizationID
LEFT JOIN Refs ON Organization.id = Refs.fromID
LEFT JOIN Tag ON Tag.id = Refs.toID

GROUP BY Organization.id

If I remove the "Person" or "Refs + Tag" JOIN, duplicates dissappear. I'm a bit confused with this problem.

Here is a link for the SQL Fiddle: http://sqlfiddle.com/#!9/6251f/3/0


Solution

  • The join to the tags/refs tables is causing each organization, and therefore the people inside that organization, to be duplicated. You may try aggregating both persons and tags in separate subqueries. The following seems to work:

    SELECT 
        org.name AS Name,
        t1.Persons,
        t2.Tags
    FROM Organization org
    LEFT JOIN
    (
        SELECT organizationID, GROUP_CONCAT(name) AS Persons
        FROM Person
        GROUP BY organizationID
    ) t1
        ON org.id = t1.organizationID
    LEFT JOIN
    (
        SELECT r.fromID, GROUP_CONCAT(t.name) AS Tags
        FROM Refs r
        LEFT JOIN Tag t
            ON t.id = r.toID
        GROUP BY r.fromID
    ) t2
        ON org.id = t2.fromID;
    

    Demo