0

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

 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

谢谢 !

4

3 回答 3

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
于 2012-08-21T14:17:40.257 回答
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  
于 2012-08-21T14:20:13.000 回答
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
于 2012-08-21T14:21:18.590 回答