数据库系统概念 第四章习题

4.1.c

select C.*, I.ID, case I.name when I.name then I.name else '-' end
from course as C natural left outer join teaches as T natural left outer join instructor as I

MySql中没有decode,可以用case来代替,如上

或者还有一种做法,使用coalesce,如下

select C.*, I.ID, coalesce(I.name, '-')
from course as C natural left outer join teaches as T natural left outer join instructor as I

4.2.b

select * from student natural join takes
union
(
	select student.*, null, null, null, null, null
    from student
    where ID not in (select ID from student natural join takes)
)
union 
(
	select null, null, null, takes.*
    from takes
    where not exists (select * from student where takes.ID=student.ID)
)

可以看到这道题的两个union中分别用到了not in 和 not exisists,not exisists应该是比较好的形式。因为如果将not in用在not exisists的地方子查询将会很长,而后者没有这个问题

 

4.5  记录一个奇怪的问题

SELECT *
FROM (
(SELECT ID as id, SUM(points*credits) as sum
FROM takes NATURAL JOIN grade_points NATURAL JOIN course
group by ID)
union 
(SELECT S.ID as id ,0 as sum
from student as S
WHERE NOT EXISTS (SELECT * FROM takes as T WHERE S.ID=T.ID)
)
) as x;

这个查询不会查到union后半部分的结果,而如果把union的两部分互换,则会有正确的结果

不知道为什么,感觉应该是数据库底层运算的原因,可能是上面的join语句造成的

 

4.16

问题:如何让一个属性a的值至少在b,c的集合中存在一个

这个不会做,可以用断言,但是基本没有数据库支持这样的断言

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值