Lucas_Santos
Lucas_Santos

Reputation: 4740

MySql query that aggregate and separe with comma

I need to do a query that return all my contact name separeted by comma's when they belong the same Group. I know how to do this in SQL Server using STUFF function, but how can I do the same in MySQL ?

Table: Group

Group_Id   Description
1          New Group
2          Birthday

Table: Contacts

ID         Name       Surname       Group_Id
1          Charlan    Alves         1
2          Lucas      Germano       2
3          Junior     dos Santos    1

What I Expect

Group_Id   Name
1          Charlan Alves, Junior dos Santos
2          Lucas Germano

Upvotes: 1

Views: 103

Answers (1)

Alma Do
Alma Do

Reputation: 37365

Use GROUP_CONCAT():

SELECT 
  Group_Id, 
  GROUP_CONCAT(CONCAT(Name, ' ', Surname)) AS group_name 
FROM 
  Contacts 
GROUP BY 
  Group_Id

Note, that default separator is , (without space after comma). You may wish to add space after comma by specifying SEPARATOR ', '

Upvotes: 1

Related Questions