左连接有多个值

时间:2015-09-01 15:59:48

标签: mysql sql

我的表格

functions_groups
+---------------+----------+
| function_name | group_id |
+---------------+----------+
| function1     | 46       |
| function1     | 47       |
| function2     | 46       |
+---------------+----------+

groups
+----------+------------+
| group_id | group_name |
+----------+------------+
| 46       | Group46    |
| 47       | Group47    |
+----------+------------+

输出

+-----------+----------------------+
| Function  | Groups               |
+-----------+----------------------+
| function1 | Group46, Group47     |
| function2 | Group46              |
+-----------+----------------------+

我的查询直到(它给我空行/单元格)

SELECT
    fg.function_name,
    GROUP_CONCAT(DISTINCT g.group_name SEPARATOR ', ') AS group_names
FROM functions_groups fg
LEFT JOIN groups g
    ON g.group_id = fg.group_id

我该如何解决这个问题,以便从左连接中获取多个值(用逗号分隔)?

1 个答案:

答案 0 :(得分:5)

我为您编写了一个数据库查询。我希望它能解决你的问题:

<强>查询

SELECT 
    f.function_name 'Function', GROUP_CONCAT(DISTINCT g.group_name) 'Groups'
FROM
    functions_groups f
        LEFT JOIN
    groups g ON g.group_id = f.group_id
GROUP BY function_name;