实验5 数据库的嵌套查询实验
-
5.1实验目的及要求
加深对嵌套查询语句的理解
-
5.2实验内容
使用IN、比较符、ANY或ALL和EXIST操作符进行嵌套查询操作
- 5.3实验步骤
5.3.1使用带IN谓词的子查询
1.查询与‘孙悟空’在同一个系学习的学生信息;
Select * from student where sdept in
(select sdept from student where sname=’孙悟空’;
比较: Select * from student where sdept =
(select sdept from student where sname=’孙悟空’);
比较: Select * from student where sdept =
(select sdept from student where sname=’孙悟空’)and sname<>’孙悟空’;
2.查询选修了课程名为‘信息系统’的学生的学号和姓名:
在mysql中:select sno,sname from student where sno in
(select sno from sc where cno in
(select cno from course where cname=’信息系统’));
3.查询选修了课程‘1’和课程‘2’的学生的学号:
Select sno from student where sno in(select sno from sc where cno=’1’)
and sno in(select sno from sc where cno=’2’);
比较:查询选修了课程‘1’或课程‘2’的学生的sno;
Select sno from sc where cno=’1’or cno=’2’;
比较连接查询:
Select A.sno from sc A,sc Bwhere A.sno=B.sno and A.cno=’1’and B.cno=’2’;
5.3.2使用带比较运算的子查询
4.查询比‘孙悟空’年龄小的所有学生的信息:
Select * from student where sage<
(select sage from student where sname=’孙悟空’);
5.3.3使用带Any,All谓词的子查询
5.查询比其他系中软件工程系某一学生年龄小的学生的姓名和年龄;
Select snmae,sage from student where sage<Any
(select sage from student where sdept=’软件工程’)
And sdept<>’软件工程’;
6.查询其他系中比软件工程系学生年龄都小的学生姓名和年龄;
select sname,sage from student were sage<ALL
(select sage from student where sdept=’软件工程’)
And sdept<>’软件工程’;
7.查询与网络工程系所有学生的年龄均不同的学生的学号,姓名和年龄:
Select sno,sname,sage from student where sage<>all
(slect sage from student where sdept=’网络工程’);
5.3.4使用带Exists谓词的子查询和相关子查询
8.查询与其他所有学生年龄均不同的学生学号,姓名和年龄:
Select sno,sname,sage from student A where not exists
(select * from student B where A.sage=B.sage and A,sn0<>B.sno);
9.查询所有选修了1号课程的学生的姓名:
Select sname from student where exists
Select sname from student where sno =student.sno and cno=’1’);
10.查询没有选修了1号课程的学生姓名:
Select sname from student where not exists
(select * from sc where sno=student.sno and cno=’1’)
11.查询选修了全部课程的学生姓名:
Select sname from student where not exists
(select * from course where not exists
(select * from sc where sno=A.sno and cno=B.cno));
12.查询至少选修了学生12002选修的全部课程的学生的学号:
Select distinct sno from sc A where not exists
(select * from sc B where sno=’12002’and not exists
(select * from sc C where sno =A.sno and cno=B.cno));
13.求没有人选修的课程号cno 和cname;
Select cno,cname from course C where not exists
(select * from sc where sc.cno=C.cno;
14.查询满足条件的(sno,cno)对,其中该学号的学生没有选修该课程号cno的课程
Select sno,cno from student,course where not exists
(select * from sc where cno=course.cno and sno=student.sno);
15.查询每个学生的课程成绩最高的成绩信息(sno,cno,grade);
Select * from sc A where grsde=
(select max(grsde)from sc where sno=A.sno);
思考:
如何查询所有学生都选修了的课程的课程号cno?
Select cno from course where not exists (select * from course where not exists(select * from sc where sno=student.sno and cno=course.cno));