3.4.3 嵌套查询
嵌套查询:将一个查询块嵌套在另一个查询块的where子句或having短句的条件中的查询称为嵌套查询。
分为父查询(外层查询)与子查询(内层查询)
【注】子查询的select语句中不能使用order by 子句
不相关子查询:子查询的查询条件不依赖于父查询(例如 例3.55和例3.56)
相关子查询:子查询的条件依赖于父查询(例如 例3.57)
1. 带有in谓词的子查询
【例3.55】查询与“刘晨”在同一个系学习的学生。
select Sno,Sname,Sdept
from Student
where Sdept in
(select Sdept
from Student
where Sname='刘晨');
它的执行顺序如下列语句:
select Sdept
from Student
where Sname='刘晨';--查询刘晨的系名
select Sno,Sname,Sdept
from Student
where Sdept='CS';--在CS系的学生信息
此外,这个例题也可以通过自身连接来实现:
select S1.Sno,S1.Sname,S1.Sdept
from Student S1,Student S2
where S1.Sdept=S2.Sdept and S2.Sname='刘晨';
例3.55的四种解法:
1.嵌套查询
select Sno,Sname,Sdept
from Student
where Sdept in
(select Sdept
from Student
where Sname='刘晨');
2.连接查询
select S1.Sno