gpt4 book ai didi

mysql - 连接多对多并将许多引用合并到单行中

转载 作者:行者123 更新时间:2023-11-29 09:42:25 24 4
gpt4 key购买 nike

我咨询过类似的问题,但问题不同,因为我不仅有多对多的联接,而且还有一对多的联接。

用户

+----+-------+---------------+
| 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_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 表连接,具有多对多和一对多的组连接功能。

查询出错。

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

最佳答案

由于每个用户的部门都是唯一的,因此您可以使用 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

此外,列的别名不得用单引号括起来。请改用反引号。

关于mysql - 连接多对多并将许多引用合并到单行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56330662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com