0

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

这是我收到的结果:

+----+--------------+--------+--------+---------------------+----------+------------------+
| 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             |
+----+--------------+--------+--------+---------------------+----------+------------------+

如您所见,第一行显示了 3 次 Linux,但这应该只列出一次。我已经看到只有当客户拥有超过 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
4

2 回答 2

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 关键字,它应该适合您

于 2013-08-27T09:36:42.957 回答
1

你只需要distinctGroup_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
于 2013-08-27T09:34:36.913 回答