子查询是指一条 SELECT 语句作为另一条 SELECT 语句的一部分,外层的 SELCT 语句称
为外部查询,内层的 SELECT 语句称为内部查询(或子查询)。子查询分两种:嵌套子查
询和相关子查询。
1.嵌套子查询
嵌套子查询的执行不依赖于外部嵌套。
嵌套子查询的执行过程为:首先执行子查询,子查询得到的结果集不被显示出来,而是传
给外部查询,作为外部查询的条件使用,然后执行外部查询,并显示查询结果。子查询可
以多层嵌套。
嵌套子查询一般也分为两种:子查询返回单个值和子查询返回一个值列表。
(1)返回单个值,该值被外部查询的比较操作(如,= 、!=、<、<=、>、>=)使用,该
值可以使子查询中使用集合函数得到的值。
【例 30】查询所有价格高于平均价格的书。
use pubs
go
select title
from titles
where price>
(select averageprice=avg(price)
from titles)
执行结果为:
title
--------------------------------------------------------------------------------
The Busy Executive's Database Guide
Straight Talk About Computers
Silicon Valley Gastronomic Treats
But Is It User Friendly?
Secrets of Silicon Valley
Computer Phobic AND Non-Phobic Individuals: Behavior Variations
Prolonged Data Deprivation: Four Case Studies
Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean
Sushi, Anyone?
(所影响的行数为 9 行)
在这个例子中,SQL Server 首先获得“select averageprice=avg(price) from titles”的结果集,该
结果集为单行单列,然后将其作为外部查询的条件执行外部查询,并得到最终的结果。
【例 31】查询书号为 pc1035 的作者的作者号、作者姓名。
use pubs
go
select au_id,au_lname,au_fname
from authors
where au_id=(select au_id
from titleauthor
where title_id='pc1035' )
得到的结果为:
au_id au_lname au_fname
----------- ---------------------------------------- --------------------
238-95-7766 Carson Cheryl
评论0