数据库系统概论第三章-带有exists谓词的子查询

表结构如下:

c表:

数据库系统概论第三章-带有exists谓词的子查询

s表:

数据库系统概论第三章-带有exists谓词的子查询

sc表:

数据库系统概论第三章-带有exists谓词的子查询

一、[44]查询所有选修了1号课程的学生姓名。

select sname from s
where exists (select* from sc where sno = s.sno and cno = '1');

数据库系统概论第三章-带有exists谓词的子查询

二、 [46] 查询选修了全部课程的学生姓名。

     数据库系统概论第三章-带有exists谓词的子查询(所有x都符合P=不存在一个x不符合P)

转换为:没有一门课程是该学生不选修的:

select sname from s
where not exits(
select * from c
where not exists(
select * from sc
where sno = s.sno and cno = c.cno
)
);

三、 [47]查询至少选修了学生200215122选修的全部课程的学生号码。

形式化表示:

  用P表示谓词 “学生200215122选修了课程y”

  q表示谓词 “学生x选修了课程y”

   (∀y)p->q

很重要的一个谓词等价转换:

∀y)p->q 等价于

﹁(∃y)(﹁(p->q)) => ﹁(∃y)(﹁(﹁p∨q))  =>  ﹁(∃y)(p∧﹁q)) 

也就是说:不存在这样的课程y,学生200215122选修了课程y,而学生x没有选

select distinct sno
from sc scx /*对于学生x*/
where not exists/*不存在这样的课程y*/
(
select * from sc scy
where scy.sno = '201215122' and not exists/*学生201215122选修了课程y 但是学生x却没选*/
(/*下面就是表达学生z选了学生201215122选的课*/
select * from sc scz
where scz.sno = scx.sno
and
scz.cno = scy.cno
)
);

对于上面的特定表里面没有学号为201215122的学生,所以改一下学号

为95001

SQL语句改为:

select distinct sno
from sc scx /*对于学生x*/
where not exists/*不存在这样的课程y*/
(
select * from sc scy
where scy.sno = '95001' and not exists/*学生201215122选修了课程y 但是学生x却没选*/
(/*下面就是表达学生z选了学生201215122选的课*/
select * from sc scz
where scz.sno = scx.sno
and
scz.cno = scy.cno
)
);

数据库系统概论第三章-带有exists谓词的子查询

ok,没有这样的学生。

上面一个查询没运行成功,明天改。