实验报告(六)
1、实验目的
(1) 掌握关联查询的用法
(2) 掌握集合查询的区别和用法
(3) 掌握EXISTS的用法
2、实验预习与准备
(1) 了解ANY,ALL的用法
(2) 了解Max,Min,In与ANY,ALL的等价规则
(3) 了解子查询的使用限制
(4) 了解非关联子查询的特点
(5) 了解关联子查询的特点
3、实验内容及步骤
(1) 查询入学成绩比本班平均入学成绩高的学生学号,姓名,班级和入学成绩(使用关联子查询)
select s.sno,s.sname,s.clno,sc.scorefrom student s,score scwhere sc.score > (select avg(score) from score) and s.sno=sc.sno;
(2) 查询没有选修“010002”号课程的学生姓名(使用Exists)
SELECT DISTINCT s.sno, s.sname
FROM student s
WHERE NOT EXISTS (SELECT *FROM score scWHERE sc.sno = s.sno AND sc.cno = '010002'
);
(3) 查询至少选修了姓名为“耿明”的学生所选修课程中一门课的学生的学号和姓名(使用Exists)
SELECT DISTINCT s.sno, s.sname
FROM student s
WHERE EXISTS (SELECT *FROM score scWHERE sc.sno = s.snoAND EXISTS (SELECT *FROM score sc2WHERE sc2.sno = '耿明'AND sc2.cno = sc.cno)
);
(4) 查询教授过张丹丹老师教授过的所有班级的教师姓名(使用Exists)
SELECT DISTINCT t.tname
FROM teacher t
WHERE EXISTS (SELECT *FROM class clWHERE EXISTS (SELECT *FROM course_class ccWHERE cc.tno = t.tnoAND cc.clno = cl.clno)AND EXISTS (SELECT *FROM course_class cc2WHERE cc2.tno = '张丹丹'AND cc2.clno = cl.clno)
);
(5) 查询入学成绩最高的和最低的学生的学号、姓名和入学成绩(集合查询)
select sno,sname,point from student where point=(select MAX(point) from student) or point=(select MIN(point) from student);
(6)查询期末平均成绩在85分以上的学生学号、姓名和出生日期
SELECT s.sno, s.sname, s.birth
FROM student s
JOIN score sc ON s.sno = sc.sno
GROUP BY s.sno, s.sname, s.birth
HAVING AVG(sc.score) > 85;
(7)查询每门课程最高分的学生的学号
SELECT cno, MAX(score) AS max_score
FROM score
GROUP BY cno;
(8)查询既选修了“大学英语”又选修了“金融学”的学生学号(至少写出使用连接查询、嵌套查询两种方法。思考:如果还要查询学生姓名呢?)
SELECT s.sno
FROM student s
JOIN score sc1 ON s.sno = sc1.sno
JOIN score sc2 ON s.sno = sc2.sno
JOIN course c1 ON sc1.cno = c1.cno
JOIN course c2 ON sc2.cno = c2.cno
WHERE c1.cname = '大学英语' AND c2.cname = '金融学';
(9)查询没有任何学生选修的课程编号和课程名称及学分(写出使用外连接, in+非关联子查询和exists+关联子查询三种方法)
-- Using LEFT JOIN
SELECT c.cno, c.cname, c.credit
FROM course c
LEFT JOIN score sc ON c.cno = sc.cno
WHERE sc.sno IS NULL;-- Using IN with a subquery
SELECT cno, cname, credit
FROM course
WHERE cno NOT IN (SELECT cnoFROM score
);-- Using EXISTS with a subquery
SELECT c.cno, c.cname, c.credit
FROM course c
WHERE NOT EXISTS (SELECT *FROM score scWHERE sc.cno = c.cno
);