数据库系统概论第三章-带有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,没有这样的学生。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值