Search code examples
mysqlsqlgroup-concat

Concat result from join


I have the following (little bit long) query :

 SELECT * 
        FROM client C
        JOIN uga U
        ON U.id_uga = C.id_uga
        JOIN appartenance A
        ON A.id_uga = U.id_uga
        JOIN serviceattribuee SA
        ON SA.id_client = C.id_client
        JOIN service S
        ON S.id_service = SA.id_service
        WHERE A.id_utilisateur = 28
        ORDER BY ville_client

Which returns me something like :

Nom : "Test" 
Adresse : "Test"
Services : "Service 1"

Nom : "Test" 
Adresse : "Test"
Services : "Service 2"


Nom : "Test 2"
Adresse : "Test 2"
Services : "Service 1"

Nom : "Test 2"
Adresse : "Test 2"
Services : "Service 2"

The thing is, as you can see, the results are duplicated, because there's several services for each client. Is there a way to concat all the services into the same row for each client, in order to avoid doubles ?

I'm using MySQL5.5

Thanks !


Solution

  • I think what you are looking for is GROUP_CONCAT with a GROUP BY clause. In order to use it well, you will need to specifically enumerate the columns you want to concat (I've shown here a sample, you can adapt to your needs:

    SELECT 
      C.*
      GROUP_CONCAT(S.Nom) as `services`
    FROM client C
      JOIN uga U
      ON U.id_uga = C.id_uga
      JOIN appartenance A
      ON A.id_uga = U.id_uga
      JOIN serviceattribuee SA
      ON SA.id_client = C.id_client
      JOIN service S
      ON S.id_service = SA.id_service
    WHERE A.id_utilisateur = 28
    GROUP BY C.id
    ORDER BY ville_client