日期:2014-05-17  浏览次数:20708 次

有两道 sql 练习题不明白,求大神们指教
表1 student表(sno,sname,ssex,sage),sno是主键
表2 teacher表(tno,tname),tno是主键
表3 course表(cno,cname,tno),cno是主键,tno是外键
表4 sc表(sno,cno,score),这是一张关联表

有这样两道我不太明白,不知道怎么做,求大家给我讲讲,感激不尽

11、查询至少有一门课与学号为“s001”的同学所学相同的同学的学号和姓名;
12、查询至少学过学号为“s001”同学所有一门课的其他同学学号和姓名;

而且我感觉第二道题讲的意思和第一道一样,我现在晕呼呼的。

------解决方案--------------------
感觉第二句话有问题,什么叫所有一门课
------解决方案--------------------
第一个问题:select sno,sname from student,sc where student.sno = sc.sno and sc.cno in (select cno from sc where sno = 's001')
第二个问题:select sno,sname from student,sc where student.sno = sc.sno and sc.cno in (select cno from sc where sno = 's001') and sc.sno <> 's001'
------解决方案--------------------
第一题帮你解了,没测试,你可以自己分析下

--s001所学课程
(select * from (select * from (select * from student where sno='s001') a0,sc b0 where a0.sno=b0.sno) a1,course b1 where a1.cno=b1.cno) a2


--所有同学课程
(select * from (select * from (select * from student) c0,sc d0 where c0.sno=d0.sno) c1,course d1 where c1.cno=d1.cno) c2

--相同课程的集合
select sno,sname from (
select * from (select * from (select * from student where sno='s001') a0,sc b0 where a0.sno=b0.sno) a1,course b1 where a1.cno=b1.cno
) a2,(
select * from (select * from (select * from student) c0,sc d0 where c0.sno=d0.sno) c1,course d1 where c1.cno=d1.cno
) c2 
where a2.cname=c2.cname

方法就是你先把需要的表单拼接起来,然后生成需要的表单后自己设置查询条件

例如,你先要把学号"s001"的课程列表生成出来,那么就要如下几个步骤

1.生成s001对应的列表
select * from student where sno='s001'

2.与课程号列表关联查询并设置条件为学号相同
select * from (select * from student where sno='s001') a0,sc b0 where a0.sno=b0.sno

3.在上面基础上继续与课程表关联查询并设置条件为课程号相同
select * from (select * from (select * from student where sno='s001') a0,sc b0 where a0.sno=b0.sno) a1,course b1 where a1.cno=b1.cno

这样你就获得了s001所学课程的表,然后你需要再生成所有学生的课表,并关联查询,且条件为课程相等

然后再读取结果中的学号和姓名即可