Search code examples
sqlgroup-byleft-joingroup-concat

sql: why does query repeat values when using 'GROUP CONCAT' + 'GROUP BY'?


The Query:

SELECT MemberId, a.MemberName, GROUP_CONCAT(FruitName) FROM a LEFT JOIN b ON 
a.MemberName = b.MemberName GROUP BY a.MemberName

Table a

MemberID          MemberName              
--------------    ----------  
1                  Al                   
1                  Al       
3                  A2       

Table b

MemberName             FruitName
---------------        --------------
Al                     Apple
Al                     Mango
A2                     Cherry

Resulting Output from above query:

MemberId    MemberName  GROUP_CONCAT(FruitName)
3           A2          Cherry
1           A1          Apple,Apple,Mango,Mango

The actual tables I am using have 10 columns apiece so just storing everything in one table is not a workaround. That said, how can I change the query to only return 'Apple,Mango' for MemberName?


Solution

  • Add the keyword DISTINCT to the grouped column:

    GROUP_CONCAT(DISTINCT FruitName)