在具有NULL值的多个表中使用LEFT JOIN

时间:2014-09-19 20:16:01

标签: mysql sql left-join

我有以下数据表结构

TABLE: USER USER ID | USER NAME 1 | Joe 2 | Mary

TABLE : USER GROUP USER ID | GROUP ID 1 | 1 1 | 2

TABLE : GROUP GROUP ID | GROUP NAME 1 | Company 1 2 | Company 2

TABLE : ROLE ROLE ID | ROLE NAME 1 | Administrator 2 | Users

TABLE : USER ROLE USER ID | ROLE ID 1 | 1 2 | 1

如您所见,用户#2不属于任何组。角色与组是可选的,迫使我离开联合,但当我运行如下查询时

`SELECT a.user_id,
        a.user_name
        GROUP_CONCAT(r.role_name) AS role_names,
        GROUP_CONCAT(g.group_name) AS group_names
 FROM  user a
  LEFT JOIN role_map m ON a.user_id = m.user_id
     INNER JOIN role r ON m.role_id = r.role_id
  LEFT JOIN user_group s ON a.user_id = s.user_id
     INNER JOIN group g ON s.group_id = g.group_id
 GROUP BY a.user_id`

我在role_names列中获得了笛卡尔积 - 结果如下所示

Joe | Administrators, Administrators | Company 1, Company 2

我做错了什么?

1 个答案:

答案 0 :(得分:2)

解决此问题的最简单方法是在DISTINCTSQL Fiddle)中使用GROUP_CONCAT。此外,您需要添加GROUP BY a.user_id才能对每个用户进行分组:

SELECT a.user_id,
       a.user_name,
       GROUP_CONCAT(DISTINCT r.role_name) AS role_names,
       GROUP_CONCAT(DISTINCT g.group_name) AS group_names
FROM  `user` a
  LEFT JOIN `user_role` m ON a.user_id = m.user_id
  LEFT JOIN `role` r ON m.role_id = r.role_id
  LEFT JOIN `user_group` s ON a.user_id = s.user_id
  LEFT JOIN `group` g ON s.group_id = g.group_id
GROUP BY a.user_id;