使用JOIN时重复GROUP_CONCAT

时间:2018-07-26 12:00:36

标签: sql group-concat

我正在创建一种地理缓存团队建设系统,但查询遇到问题。

要对照我使用的团队GROUP_CONCAT来整理和显示个人,但是当我尝试包括位置(列为markers)时,个人姓名会根据标记。

我整理了SQL Fiddle来解释自己的工作方式。

这是我的查询:

SELECT SQL_CALC_FOUND_ROWS
            map_team.id AS team_id,
            map_team.name,
            GROUP_CONCAT(firstname, ' ', surname SEPARATOR ', ') AS full_name
            FROM map_team
            LEFT JOIN members
                ON members.map_team=map_team.id
            WHERE members.map_team IS NOT NULL
            GROUP BY map_team.name
            ORDER BY map_team.name ASC

任何建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

使用

GROUP_CONCAT(distinct firstname ...

答案 1 :(得分:1)

使用以下查询:

SELECT SQL_CALC_FOUND_ROWS
    map_team.id AS team_id,
    map_team.name,
    GROUP_CONCAT(distinct firstname, ' ', surname SEPARATOR ', ') AS full_name,
    count(*) AS total_markers,
    SUM(IF(status = 'completed', 1, 0)) AS total_completed
    FROM map_team
    LEFT JOIN members
        ON members.map_team=map_team.id
    LEFT JOIN map_markers
        ON map_markers.team_id=map_team.id
    WHERE members.map_team IS NOT NULL
    GROUP BY map_team.name
    ORDER BY map_team.name ASC

答案 2 :(得分:1)

GROUP_CONCAT( distinct ... )将不会给出正确的答案,因为团队中的团队成员姓名可以相同。如果要在单个查询中获取它,可以使用:

SELECT SQL_CALC_FOUND_ROWS
    map_team.id AS team_id,
    map_team.name,
    GROUP_CONCAT(firstname, ' ', surname SEPARATOR ', ') AS full_name,
    (select count(*) from map_markers where team_id = map_team.id) AS total_markers,
    (select count(*) from map_markers where team_id = map_team.id and status = 'completed') AS total_completed
    FROM map_team
    LEFT JOIN members
        ON members.map_team=map_team.id
    WHERE members.map_team IS NOT NULL
    GROUP BY map_team.name
    ORDER BY map_team.name ASC

如果您不喜欢select中的子查询的想法。您需要单独进行操作。