日期:2014-05-16  浏览次数:20789 次

哪位大神帮忙看看这种查询该怎么实现
a表:
id name 
1 张三
2 李四
3 王五
4 赵六

b表:
id class aId
1 1 1
2 1 2
3 2 3
4 1 4


查询class=1的所有人的姓名
显示结果为:
class name
1 张三,李四,赵六

------解决方案--------------------
select b.class,group_concat(a.name) from a inner join b
on a.id=b.aid group by b.class
------解决方案--------------------
SQL code
root@localhost : test 04:32:29>select * from a;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 张三   |
|    2 | 李四   |
|    3 | 王五   |
|    4 | 赵六   |
+------+--------+
4 rows in set (0.00 sec)

root@localhost : test 04:32:33>select * from b;
+------+-------+------+
| id   | class | aid  |
+------+-------+------+
|    1 |     1 |    1 |
|    2 |     1 |    2 |
|    3 |     2 |    3 |
|    4 |     1 |    4 |
+------+-------+------+
4 rows in set (0.00 sec)

root@localhost : test 04:32:34>select class,group_concat(name) as name from a,b where a.id=b.aid and class=1 group by class;+-------+----------------------+
| class | name                 |
+-------+----------------------+
|     1 | 张三,李四,赵六       |
+-------+----------------------+
1 row in set (0.00 sec)

------解决方案--------------------
GROUP_CONCAT(DISTINCT test)