1

问题:我想将子查询的结果合并为一个文本字段,结果用逗号(或任何符号)分隔到主查询的结果中。

例子:

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

任何帮助将不胜感激。

4

3 回答 3

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文档以获取更多信息。

于 2012-04-09T05:28:10.250 回答
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
于 2012-04-09T05:34:52.167 回答
0
select a.user_ID,a.user,b.roles 
from table1 as a, table2 as b 
where a.user_ID=b.user_ID
于 2012-04-09T06:02:13.153 回答