2012-04-10 90 views
6

問題:我有一個GROUP_CONCAT查詢按預期工作,但我想使concat成爲聯接答案,而不是原始ID字段。添加一個內部連接到mySQL GROUP_CONCAT語句

目前查詢:

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 | 
+----------+-----------+ 

回答

15

嘗試以下查詢

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 
+0

塔維克拉姆 - 這個工程 – Laurence 2012-04-10 07:58:04