数据库系统概论第三章-带有exists谓词的子查询
表结构如下:
c表:
s表:
sc表:
一、[例44]查询所有选修了1号课程的学生姓名。
select sname from s
where exists (select* from sc where sno = s.sno and cno = '1');
二、 [例46] 查询选修了全部课程的学生姓名。
(所有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
)
);
ok,没有这样的学生。
上面一个查询没运行成功,明天改。