7

問題:意図したとおりに機能する GROUP_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   |
+----------+-----------+
4

1 に答える 1

22

次のクエリを試してください

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
于 2012-04-10T06:56:16.283 に答える