向 mySQL GROUP_CONCAT 语句添加内连接
Posted
技术标签:
【中文标题】向 mySQL GROUP_CONCAT 语句添加内连接【英文标题】:Add an inner join to mySQL GROUP_CONCAT statement 【发布时间】:2012-04-22 11:36:43 【问题描述】:问题:我有一个按预期工作的 GROUP_CONCAT 查询,但我想让 concat 成为连接答案,而不是原始 ID 字段。
当前查询:
SELECT user.user_id, user.user, GROUP_CONCAT(user_roles.roleID separator ', ') roles
FROM user
JOIN user_roles ON user.user_ID = user_roles.user_ID
GROUP BY users.user_ID, users.user
给出结果:
+----------+---------+----------------------------+
| user_ID | user | roles |
+----------+---------+----------------------------+
| 1 | Smith | 1, 3 |
+----------+---------+----------------------------+
| 2 | Jones | 1, 2, 3 |
+----------+---------+----------------------------+
期望的结果:
+----------+---------+----------------------------+
| user_ID | user | roles |
+----------+---------+----------------------------+
| 1 | Smith | Admin, Other |
+----------+---------+----------------------------+
| 2 | Jones | Admin, Staff, Other |
+----------+---------+----------------------------+
用户表:
+----------+---------+
| user_ID | user |
+----------+---------+
| 1 | Smith |
+----------+---------+
| 2 | Jones |
+----------+---------+
*users_roles 表:*
+----------+---------+
| user_ID | role_ID |
+----------+---------+
| 1 | 1 |
+----------+---------+
| 2 | 1 |
+----------+---------+
| 2 | 2 |
+----------+---------+
| 2 | 3 |
+----------+---------+
| 1 | 3 |
+----------+---------+
角色表:
+----------+-----------+
| role_ID | role_name |
+----------+-----------+
| 1 | Admin |
+----------+-----------+
| 2 | Staff |
+----------+-----------+
| 3 | Other |
+----------+-----------+
【问题讨论】:
【参考方案1】:尝试以下查询
SELECT user.user_id, user.user, GROUP_CONCAT(roles.role_name separator ', ') roles
FROM user
JOIN user_roles ON user.user_ID = user_roles.user_ID
JOIN roles ON user_roles.role_ID= user_roles.role_ID
GROUP BY users.user_ID, users.user
【讨论】:
以上是关于向 mySQL GROUP_CONCAT 语句添加内连接的主要内容,如果未能解决你的问题,请参考以下文章
在 Codeigniter/MYSQL 中将选定属性添加到 group_concat 输出
mysql存储过程group_concat为游标中的选择返回null