文章目录

  • ​​嵌套查询​​
  • ​​带有in谓语的子查询​​
  • ​​带有比较运算符的子查询​​
  • ​​带有any(some)或all谓词的子查询​​
  • ​​带有exists谓词的子查询​​

嵌套查询


第三章 嵌套查询_比较运算符

带有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='刘晨'


第三章 嵌套查询_Sage_02

带有比较运算符的子查询

--查询与刘晨在同一个系的学生
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谓词的子查询


第三章 嵌套查询_Sage_03

--查询非计算机科学系中比计算机科学系任意一个学生年龄小的学生姓名和年龄
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')