SQL Server 查询选修了学分为3和4课程的学生名字(四种方法)

物理模型和各表的数据图如下:

 SQL语句:

--自然连接
select distinct  sname from 学生 s,选课 e,课程 c,选课 e1,课程 c1
where s.sid=e.sid 
and e.cid=c.cid
and s.sid=e1.sid
and e1.cid=c1.cid
and c.credit=3 and c1.credit=4
--in连接
select distinct sname  from 学生
where 学生.sid in(select 选课.sid from 选课
where 选课.cid in (select 课程.cid from 课程 
where 课程.credit=3 )
and 学生.sid in(select 选课.sid from 选课
where 选课.cid in (select 课程.cid from 课程 
where 课程.credit=4 )))
--join连接
select distinct sname from 学生 s
join 选课 e on s.sid=e.sid 
join 课程 c on e.cid=c.cid
join 选课 e1 on s.sid=e1.sid
join 课程 c1 on e1.cid=c1.cid
and c.credit=3 and c1.credit=4
--exists 连接
select distinct sname  from 学生
where exists(select * from 选课
where 学生.sid=选课.sid 
and exists (select * from 课程 
where 课程.cid=选课.cid and 课程.credit=3 )
and exists (select * from 选课
where 选课.sid=学生.sid 
and exists (select * from 课程 
where 课程.cid=选课.cid and 课程.credit=4 )))

为了凸显各个方法的专一性,所以没有采用各个结合的方法,所以最后的SQL语句可能会有些许繁琐,欢迎大家提出更简洁的SQL语句!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vous oublie@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值