首页 新闻 会员 周边

多对对关系查询

0
悬赏园豆:5 [已解决问题] 解决于 2010-12-01 21:07

学生表

Stu_id

Stu_name

1

张三

2

李四

3

王五

 

课程表

Co_id

Co_name

1

Java

2

C#

3

C

4

C++

5

Javascript

 

关系表

Stu_id

Co_id

1

1

1

4

2

1

2

3

2

5

 

 

前几天去面试被问了一道关于数据库的问题。到现在也没找到答案。

题目是这样的:有学生表、课程表和关系表,查出学生所选的课程。

我当时就想通过连接查询。当然这样的话会出现重复出现同一个学生姓名的情况。如:

 

张三

Java

张三

C++

 

可是题目要求出现的情况是:张三 java,c++

请问这个SQL该如何写。

遥远的记忆的主页 遥远的记忆 | 初学一级 | 园豆:199
提问于:2010-12-01 17:18
< >
分享
最佳答案
0

select Stu_name,stuff(select ',' + Co_name

             from 课程表

             where Co_id=g.Co_id for xml path(''),1,1'') as 课程

from 学生表 as x inner join  关系表 as g on x.Stu_id=g.Stu_id

收获园豆:5
Quentin lee | 菜鸟二级 |园豆:230 | 2010-12-01 17:55
我运行这个语句的时候还是不符合要求。不过给了我解题方向。这是最重要的。
遥远的记忆 | 园豆:199 (初学一级) | 2010-12-03 12:22
其他回答(6)
0

看不太明白!!

後浪 | 园豆:830 (小虾三级) | 2010-12-02 08:53
0

答案也完全没看懂

松鼠鱼 | 园豆:185 (初学一级) | 2010-12-02 09:56
0

佩服答案人,昨天想半天只想到临时表

花祭果凛 | 园豆:310 (菜鸟二级) | 2010-12-02 10:55
刚刚搜索了下 for xml path('')大致了解用法了,学到了
支持(0) 反对(0) 花祭果凛 | 园豆:310 (菜鸟二级) | 2010-12-02 11:05
select stu_id,co_id,(select convert(varchar(20),co_id)+',' from t3 where a.stu_id=stu_id for xml path('')) from t3 a 嘎嘎,这是我试验的 for xml path(''),逻辑太丑了,至少得到 stu_id 1(1,4,) stu_id 2(1,3,5,)
支持(0) 反对(0) 花祭果凛 | 园豆:310 (菜鸟二级) | 2010-12-02 11:14
select distinct stu_id,(select convert(varchar(20),co_id)+',' from t3 where a.stu_id=stu_id for xml path('')) from t3 a select distinct stu_name,(select convert(varchar(20),co_id)+',' from t3 where a.stu_id=stu_id for xml path('')) from t3 a,t1 b where a.stu_id=b.stu_id select distinct stu_name,stuff((select ','+co_name from t3,t2 where a.stu_id=stu_id and t3.co_id=t2.co_id for xml path('')),1,1,'') from t3 a,t1 b where a.stu_id=b.stu_id
支持(0) 反对(0) 花祭果凛 | 园豆:310 (菜鸟二级) | 2010-12-02 11:35
不错!
支持(0) 反对(0) tian_z | 园豆:158 (初学一级) | 2010-12-02 13:10
嘎嘎~谢谢夸奖
支持(0) 反对(0) 花祭果凛 | 园豆:310 (菜鸟二级) | 2010-12-02 13:57
0

根据题目意思我首先判断哪张是主表让后得到主表的详细信息,

据题目意思是关系表为主表,而其他的为基本信息表。这样SQL就可以得出来了

select b.stu_name,c.co_name
from
relation a
left join student b on a.stu_id=b.stu_id
left join course c on a.co_id=c.co_id
where b.stu_name='张三'

来壶清茶 | 园豆:190 (初学一级) | 2010-12-02 13:33
0

SELECT     dbo.Stu.Stu_name, dbo.Co.Co_nameFROM         dbo.Co INNER JOIN                      dbo.T3 ON dbo.Co.Co_id = dbo.T3.Co_id INNER JOIN                      dbo.Stu ON dbo.T3.Stu_id = dbo.Stu.Stu_idWHERE     (dbo.Stu.Stu_name = '张三')

yuqicook | 园豆:205 (菜鸟二级) | 2010-12-02 22:14
0

牛人,都是牛人。已经学完SQL有一年了,还不知道有这种用法。长见识了~

feichexia | 园豆:205 (菜鸟二级) | 2010-12-10 19:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册