问题:我想将子查询的结果组合为文本字段,结果用逗号(或任何符号确实)分隔成主查询的结果。
示例:
表1:
+----------+---------+
| user_ID | user |
+----------+---------+
| 1 | Smith |
+----------+---------+
| 2 | Jones |
+----------+---------+
表1:
+----------+---------+
| user_ID | roles |
+----------+---------+
| 1 | Admin |
+----------+---------+
| 2 | Staff |
+----------+---------+
| 2 | Admin |
+----------+---------+
| 2 | Super |
+----------+---------+
| 1 | Other |
+----------+---------+
结果将是:
+----------+---------+----------------------------+
| user_ID | user | roles |
+----------+---------+----------------------------+
| 1 | Smith | Admin, Other |
+----------+---------+----------------------------+
| 2 | Jones | Staff, Admin, Super |
+----------+---------+----------------------------+
非常感谢任何帮助。
答案 0 :(得分:4)
试试这个:
select t1.user_id, t1.user, group_concat(t2.roles separator ', ') roles
from t1
join t2 on t1.user_id = t2.user_id
group by t1.user_id, t1.user
查看GROUP_CONCAT
文档以获取更多信息。
答案 1 :(得分:0)
试试这个并告诉我它是否有帮助:
select a.user_id, a.user, group_concat(b.roles) as roles
from table1 as a
join table2 as b on a.user_id = b.user_id
group by a.user_id
答案 2 :(得分:0)
select a.user_ID,a.user,b.roles
from table1 as a, table2 as b
where a.user_ID=b.user_ID