我曾咨询过类似的问题,但问题却有所不同,因为我加入的不仅是很多对很多,而且是一对多。
用户
+----+-------+---------------+
| id | first | department_id |
+----+-------+---------------+
| 1 | John | 1 |
| 2 | Jane | 2 |
+----+-------+---------------+
部门
+----+------------+
| id | name |
+----+------------+
| 1 | purchasing |
| 2 | HR |
| 3 | marketing |
+----+------------+
角色
+----+----------+
| id | name |
+----+----------+
| 1 | admin |
| 2 | accounts |
| 3 | sales |
+----+----------+
user_role
+--------+----------+
| user_id | role_id |
+--------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 2 |
| 2 | 3 |
+--------+----------+
sql
SELECT user.first, GROUP_CONCAT(role.name), department.id AS 'department.id', department.name AS 'department.name'
FROM user
INNER JOIN department ON user.department_id
INNER JOIN user_role ON user.id = user_role.user_id
INNER JOIN role ON user_role.role_id = role.id
GROUP BY user.name;
期望
John, "admin,accounts,sales", 1, purchasing
Jane, "accounts,sales", 2, HR
从本质上讲,这是一个4表联接,具有多对多和1对多的组连接功能。
查询给出错误。
Error Code: 1055. Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'department.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
答案 0 :(得分:1)
由于部门对每个用户都是唯一的,因此您可以使用max()
来获取部门详细信息,以克服group by
带来的限制。
SELECT
user.first,
GROUP_CONCAT(role.name) AS roles,
max(department.id) AS department_id,
max(department.name) AS department_name
FROM user
INNER JOIN department ON user.department_id = department.id
INNER JOIN user_role ON user.id = user_role.user_id
INNER JOIN role ON user_role.role_id = role.id
GROUP BY user.first;
此外,如果用户名不是唯一的,则您应该:
GROUP BY user.id, user.first
此外,列别名也不能用单引号引起来。请改用反引号。