第三章 嵌套查询

嵌套查询

带有in谓语的子查询

--查询与刘晨在同一个系的学生
select Sno,Sname,Sdept
from Student
where Sdept in
		(select Sdept
		from Student
		where Sname='刘晨';
		)
--本例中 子查询的查询条件不依赖父查询,称为不相干子查询
-----------------------------------------------------
--本例中的查询也可以用自身连接来完成
select S1.Sno,S1.Sname,S1.Sdept
from Stuent S1,Student S2
where S1.Sdept=S2.Sdept and S2.Sname='刘晨'

带有比较运算符的子查询

--查询与刘晨在同一个系的学生
select Sno,Sname,Sdept
from Student
where Sdept=
		(select Sdept
		from Student
		where Sname='刘晨';
		)
-----------------------------------------------------
--查询每个学生超过他自己选修课程平均成绩的课程号
select Sno,Cno
from SC x
where Grade>=(select avg(Grade)
			from SC y
			where y.Sno=x.Sno
			)
--本例为一个相干子查询

带有any(some)或all谓词的子查询

--查询非计算机科学系中比计算机科学系任意一个学生年龄小的学生姓名和年龄
select Sname,Sage
from Student
where Sage<any(select Sage
				from Student
				where Sdept='CS')
			and Sdept<>'CS'		--父查询块条件
-----------------------------------------------------------
--使用聚集函数实现
select Sname,Sage
from Student
where Sage	<
				(select max(Sage)
				from Student
				where Sdept='CS')
			 and Sdept<>'CS'
--通常来说用聚集函数实现子查询通常比直接用any或all查询效率要高		

带有exists谓词的子查询

exists代表存在量词∃。带有exists谓词的子查询不返回任何数据,只产生逻辑真值“true”或逻辑假值“false”

--查询选修了1号课程的学生姓名
select Sname
from Student
where exists
			(select*								--一般情况都用* 应为exists的子查询只返回真假值
			from SC
			where Sno=Student.Sno and Cno='1')
--使用存在量词exists后,若内层查询结果非空,则外层的where子句返回真值,否则返回假值
-----------------------------------------------------------
--查询没有选修1号课程的学生姓名
select Sname
from Student
where not exists
			(select*							
			from SC
			where Sno=Student.Sno and Cno='1')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值