实验目的
掌握复杂数据查询操作。
实验内容
掌握各种连接查询、嵌套查询的使用。
实验过程(还是使用实验一的表)
1. 查询每个学生及其选课情况
select student.sno,sname,ssex,sage,sdept,cno,grade
from student,sc
where student.sno=sc.sno
2. 查询每门课的间接先修课
select first.cno,second.cpno
from course first,course second
where first.cpno=second.cno
3. 将STUDENT,SC进行右连接
select student.sno,sname,ssex,sage,sdept,cno,grade
from student right outer join sc on student.sno=sc.sno
4. 查询既选修了2号课程又选修了3号课程的学生姓名、学号
select student.sno,sname
from student inner join sc on student.sno=sc.sno
where cno='3' and sc.sno in
(select sno
from sc
where cno='2')
5. 查询和刘晨同一年龄的学生
select student.sno,sname
from student
where sname!='刘晨' and sage=
(select sage
from student
where sname='刘晨')
6. 选修了课程名为“数据库”的学生姓名和年龄
select sname,sage
from student
where sno in
(select sno
from sc
where cno in
(select cno
from course
where cname='数据库'))
7. 查询其他系比IS系任一学生年龄小的学生名单
select student.sno,sname
from student
where sdept<>'IS' and
sage<any
(select sage
from student
where sdept='IS')
8. 查询其他系中比IS系所有学生年龄都小的学生名单
select student.sno,sname
from student
where sdept<>'IS' and
sage<all
(select sage
from student
where sdept='IS')
9. 查询选修了全部课程的学生姓名
select sname
from student
where Sno in
(select Sno from SC
group by Sno
having count(*) = (select count(*) from course ))
10. 查询计算机系学生及其性别是男的学生
select student.sno,sname
from student
where sdept='IS' and ssex='男'
11. 查询选修课程1的学生集合和选修2号课程学生集合的差集
select sno
from sc
where cno='1' except
select sno
from sc
where cno='2'
12. 查询李丽同学不学的课程的课程号
select cno
from course
where cno not in
(select cno
from sc
where sno in
(select sno
from student
where sname='李丽'))
13. 查询选修了3号课程的学生平均年龄
select avg(sage) as avgsage
from student inner join sc on student.sno=sc.sno
where cno='3'
14. 求每门课程学生的平均成绩
select cno,avg(grade) as avggrade
from sc
group by cno
15. 统计每门课程的学生选修人数(超过3人的才统计)。要求输出课程号和选修人数,结果按人数降序排列,若人数相同,按课程号升序排列
select course.cno '课程号', count(sc.sno) '人数'
from course,sc
where course.cno=sc.cno
group by course.cno
having count(sc.sno)>3
order by count(sc.sno) desc,course.cno asc
16. 查询学号比刘晨大,而年龄比他小的学生姓名
select sname
from student
where sno>(select sno from student where sname='刘晨')
and
sage<(select sage from student where sname='刘晨')
17. 求年龄大于所有女同学年龄的男同学姓名和年龄
select sname,sage
from student
where ssex='男' and
sage>(select max(sage) from student where ssex='女')
实验总结
1. 分组group by 要用having来限制条件
2. desc是降序,asc是升序
3. any()是任意,all()是所有