Search code examples
phpsqlleft-joingroup-concat

GROUP_CONCAT with LEFT OUTER JOIN of two tables


SELECT table1.value, table2.additionalinfo
FROM table1
LEFT OUTER JOIN table2
ON table1.ID=table2.ID

I try to output something like this

Value   AdditionalInfo
blah    something, somethingelse, more
blah2   NULL
blah3   stuff

but I get

Value   AdditionalInfo
blah    something
blah    somethingelse
blah    more
blah2   NULL
blah3   stuff

I tried to use GROUP_CONCAT and GROUP_CONCAT(DISTINCT)

SELECT GROUP_CONCAT(table1.value), table2.additionalinfo
FROM table1
left outer JOIN table2
ON table1.ID=table2.ID ORDER BY table1.value

When I add GROUP_CONCAT and ORDER BY table1.value it lists just one additionalinfo per value but none of the values and doesn't get the repeated additionalinfos. I moved the order by all around to no avail.


Solution

  • I think you need to do GROUP_CONCAT on AdditionalInfo Column and not on table1.value

    SELECT table1.value, 
    GROUP_CONCAT(distinct table2.additionalinfo) additionalinfo
    FROM table1
    left outer JOIN table2 ON table1.ID=table2.ID 
    GROUP BY table1.value
    ORDER BY table1.value