(一) 嵌套查询
1. 求选修了’MA’的学号和姓名。
SQL> select sno,sname from student where sno in(select sno from sc where cno=(select cno from course where cname=\'数学\'));
2. 查询与刘明在同一个系学习的学生。
SQL> select * from student where sdept=(select sdept from student where sname=\'刘明\');
3. 求选修1号课程的成绩高于刘晨的成绩(指刘明选修的所有的课程的成绩)的学生学号及成绩。
SQL> select sno,grade from sc where cno=\'1\' and grade>all(select grade from sc where sno=(select sno from student where sname=\'刘明\'));
4. 求其他系中比计算机系某一学生年龄小的学生(即年龄小于计算机系年龄最大者的学生)。
SQL> select * from student where sdept!=\'CS\' and sage<any(select sage from student where sdept=\'CS\');
5. 求其他系中比计算机系学生年龄都小的学生姓名及年龄。
SQL> select sname,sage from student where sdept!=\'CS\' and sage<all(select sage from student where sdept=\'CS\');
6. 求没有选修3号课程的学生姓名。
SQL> select sname from student where sno not in(select sno from sc where cno=\'3\');
7. 查询选修了全部课程的学生姓名。
SQL> select sname from student where not exists(select * from course where not exists (select * from sc where sno=student.sno and cno=course.cno));
SQL语言中没有全称量词∨(,all)。但是可以把带有全称量词的谓词转换为等价的带有存在量词的谓词。(∨x)P≡∟(exists x(∟P))
试做:查询所有学生都选修的课程名
SQL> select cname from course where not exists(select * from student where not exists(select * from sc where sc.sno=student.sno and sc.cno=course.cno));
8. 求至少选修了学号为“20070002”的学生所选修全部课程的学生学号和姓名。
SQL> select sno,sname from student where sno in(select distinct sno from sc scx where not exists(select * from sc scy where scy.sno=\'20070002\' and not exists(select * from sc scz where scz.sno=scx.sno and scz.cno=scy.cno)));
9. 求选修课程超过2门的学生的学号和姓名。
SQL> select sno,sname from student where sno in(select sno from sc group by sno having count(*)>=2);
二、数据更新
1.插入数据
1)向Student表中插入2行数据,1行为你的信息,另一行自定。
insert into student(sno,sname,ssex,sage,sdept) values(20143985,\'陈健军\',\'男\',20,\'CS\');
insert into student(sno,sname,ssex,sage,sdept) values(20144065,\'徐诚武\',\'男\',20,\'CS\');
截图如下:
2)向Course表中插入数据,1行为本门课程的信息,另一行自定。
SQL> insert into course(cno,cname,cpno,ccredit) values(8,\'数据库系统概论\',5,5);
SQL> insert into course(cno,cname,cpno,ccredit) values(9,\'JAVA\',7,6);
截图如下
3)向SC表中插入数据,插入你的这门课程的选课信息。
SQL> insert into sc(sno,cno,grade) values(20143985,5,98);
截图如下:
2.修改数据
1)将姓刘的同学删除。
SQL> delete from student where sname like \'刘%\';
截图如下:
2)将’CS’系同学的选课信息中的成绩置0。
SQL> update sc set grade=0 where sno in(select sno from student where sdept=\'CS\');
截图如下:
3.删除数据
1)删除和’李佳’在同一个系的学生的信息。
SQL> delete from student where sdept=(select sdept from student where sname=\'李佳\');
截图如下:
2)删除’CS’系同学的选课信息。
SQL> delete from sc where sno in(select sno from student where sdept=\'CS\');
截图如下:
实验分析:
在本次数据库实验中,我完成了实验要求。本次实验内容是关于嵌套查询,在课堂上,老师讲授了嵌套查询相关知识,我也用笔练习写了sql语句,但是感觉印象还不是很深刻,有些不太理解。在实验课中我练习了sql语句,对课堂上所学的知识有了更深的理解,收获很多。实验中,我遇到了一些问题,通过查询资料和老师同学帮助最终解决了。遇到的问题如下:
1、在嵌套查询时,我感觉有点混乱,不知道怎么写,然后我后来一步步分析,先写好一个小的查询作为另一个查询的查询条件,一步步编写,查询就完成了。
2、在写关于exists的嵌套查询时,我感觉很难,查阅相关的资料后,明白了除法经常用exists实现。一般像至少、包括这样的题意时,关系代数要用除法实现,然后除法在sql语句中可以转化为两重not exists实现。
在本次实验中感觉收获很多,很开心。