数据库作业8:SQL练习5 | 您所在的位置:网站首页 › 数据库查询年龄大于19岁 › 数据库作业8:SQL练习5 |
EXISTS:存在量词,带有EXISTS谓词的子查询不返回任何数据:若where查询结果非空,产生逻辑真值‘true’;若where查询结果为空,产生逻辑假值‘false’。 由EXISTS引出的子查询,其目标列表达式通常都用 * ,因为带EXISTS的子查询只返回真值或假值,给出列名无实际意义。 [3.60]查询所有选修了1号课程的学生姓名。 方法一:等值连接 select sname from student,sc where student.sno = sc.sno and sc.cno='1';方法二:exists查询 select sname from student where exists( select * from sc where sno=student.sno and cno='1');两种方法的最终结果相同: [3.61] 查询没有选修1号课程的学生姓名。 select sname from student where not exists (select * from sc where sno=student.sno and cno='1');由于where后的exists只返回真值或者假值,因此,student表中的即使未选课(sc表中不存在)的学生姓名也会被查询到。 查询结果: 这个我也使用了第二种方法,但最终结果是错误的: select sname from student,sc where student.sno = sc.sno and sc.cno'1';原因:一个同学可以选择多门课程,比如A同学选了1,2,3号课程,如果使用上面语句,在1号课比对的时候,是不会有问题的;但2号课比对的时候因为符合条件,该同学的姓名将会被显示出来。 [3.62]查询与“刘晨”在同一个系学习的学生。 方法一:exists嵌套查询 select sno,sname,sdept from student s1 where exists (select * from student s2 where s2.sdept=s1.sdept and s2.sname='刘晨');方法二:in嵌套查询: select sno,sname,sdept from student s1 where sdept in (select sdept from student where sname='刘晨');方法三:等值连接查询 select fir.sno,fir.sname,fir.sdept from student fir,student sec where sec.sname='刘晨' and fir.sdept=sec.sdept查询的最终结果是相同的: [3.63]查询选修了全部课程的学生姓名。 SQL语言中没有全称量词,但我们可以通过存在量词间接表达全称量词: ( ∀ x ) P ≡ (\forall x) P \equiv (∀x)P≡ ¬ ( ∃ x ( ¬ P ) ) \neg(\exists x(\neg P)) ¬(∃x(¬P)) select sno,sname,sdept from student where not exists //若下层返回F,则该层返回T (select * from course where not exists //对于该学号来说是否选了所有课程,若是,则返回F (select * from sc where sno=student.sno and cno = course.cno) );not exists中,若内层查询结果非空,则外层的WHERE子句返回假值;若内层查询结果为空,则外层的WHERE子句返回真值。 集合查询集合操作的种类 并-UNION 交-INTERSECT 差-EXCEPT 并-UNION UNION:将多个查询结果合并起来时,系统自动去掉重复元组。 UNION ALL:将多个查询结果合并起来时,保留重复元组。 [3.64]查询计算机科学系的学生及年龄不大于19岁的学生。 select * from student where sdept='cs' union select * from student where sage |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |