使用group_concat和join重复值

时间:2013-08-27 09:32:57

标签: mysql sql

我对以下查询有一点问题。它返回多个值。

以下是我收到的结果:

+----+--------------+--------+--------+---------------------+----------+------------------+
| id | company      | county | vm     | os                  | products | sn               |
+----+--------------+--------+--------+---------------------+----------+------------------+
| 1  | ABC Corp     | USA    | VMW    | Linux, Linux, Linux | 3        | A123, B234, A343 |
| 2  | DEF Corp     | USA    | CIT    | Windows             | 1        | I223             |
+----+--------------+--------+--------+---------------------+----------+------------------+

正如您所看到的,第一行显示Linux的3倍,但这应该只列出一次。我已经看到,如果客户有超过1个产品,则只会出现此问题。我想我必须将我的查询分组或类似的东西,但我不知道如何。

这是我的查询:

SELECT
    customer.id,
    customer.company,
    countries.en AS country,
    vmenv.name AS vm,
    GROUP_CONCAT(operatingsystems.name SEPARATOR ', ') AS os,
    COUNT(device2customer.sn) AS products,
    GROUP_CONCAT(device2customer.sn SEPARATOR ', ') AS sn
FROM
    customer

LEFT JOIN
    countries
ON
    customer.country = countries.id

LEFT JOIN
    vmenv2kunden
ON
    vmenv2kunden.customerid = customer.id

LEFT JOIN
    vmenv
ON
    vmenv2kunden.vmenvnr = vmenv.id

LEFT JOIN
    operatingsystems2customer
ON
    operatingsystems2customer.customerid = customer.id

LEFT JOIN
    operatingsystems
ON
    operatingsystems2customer.osnr = operatingsystems.id

LEFT JOIN
    device2customer
ON
    device2customer.kundenid = customer.id

GROUP BY
    customer.id

2 个答案:

答案 0 :(得分:2)

在您的查询中,将group_concat语句更改为

GROUP_CONCAT(DISTINCT operatingsystems.name SEPARATOR ', ') AS os,
COUNT(DISTINCT device2customer.sn) AS products,
GROUP_CONCAT(DISTINCT device2customer.sn SEPARATOR ', ') AS sn

通过添加DISTINCT关键字,它应该适合你

答案 1 :(得分:1)

您只需要在distinct中使用Group_concat

请尝试以下更新的查询。

SELECT
    customer.id,
    customer.company,
    countries.en AS country,
    vmenv.name AS vm,
    GROUP_CONCAT(distinct operatingsystems.name SEPARATOR ', ') AS os,
    COUNT(device2customer.sn) AS products,
    GROUP_CONCAT(device2customer.sn SEPARATOR ', ') AS sn
FROM
    customer

LEFT JOIN
    countries
ON
    customer.country = countries.id

LEFT JOIN
    vmenv2kunden
ON
    vmenv2kunden.customerid = customer.id

LEFT JOIN
    vmenv
ON
    vmenv2kunden.vmenvnr = vmenv.id

LEFT JOIN
    operatingsystems2customer
ON
    operatingsystems2customer.customerid = customer.id

LEFT JOIN
    operatingsystems
ON
    operatingsystems2customer.osnr = operatingsystems.id

LEFT JOIN
    device2customer
ON
    device2customer.kundenid = customer.id

GROUP BY
    customer.id