来自加入的Concat结果

时间:2012-08-21 14:15:00

标签: mysql sql group-concat

我有以下(有点长)查询:

 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

返回给我的是:

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"

正如您所看到的,结果是重复的,因为每个客户端都有多个服务。 有没有办法将所有服务连接到每个客户端的同一行,以避免双打?

我正在使用MySQL5.5

谢谢!

3 个答案:

答案 0 :(得分:3)

    SELECT c.Nom, c.Adresse, 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.Nom, c.Adresse

答案 1 :(得分:2)

您想要分组并使用group_concat:

select nom, addresse, ville_client,
       group_concat(services separator ', ')
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
group by nom, addresse, ville_client
WHERE A.id_utilisateur = 28
ORDER BY ville_client  

答案 2 :(得分:2)

我认为您正在寻找的是具有GROUP BY子句的GROUP_CONCAT。为了更好地使用它,您需要专门枚举您想要连接的列(我在这里展示了一个示例,您可以根据自己的需要进行调整:

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