相关子查询
与非相关子查询
1
:标量子查询
(
相对于多值子查询
)
:
只有标量子查询返回的是单个记录或者不返回,就是有效的子查询。
Ex1:
select
OrderId
From
Orders
where
EmployeeId
=
(
select
EmployeeId
From
employees
where
lastName
like
N
'Davolio'
)
将
’Davolio’
改为
'D%'
时
,
这个时候子查询中返回结果为
2
行
,
等号右边此时为多值
,
查询失败
.
将
’=’
改为
in
谓词
.
查询才能通过
.
employees
表中无
lastname=’jason’,
外部查询将返回
null.
2
:非相关子查询(嵌套子查询)
一个
select...From...Where
查询语句块可以嵌套在另一个
select...From...Where
查询块的
Where
子
句
中,称为嵌套查询。外层查询称为父查询,主查询。内层查询称为子查询,从查询。
子查询可以嵌套多层,子查询查询到的结果又成为父查询的条件。子查询中不能有
order by
分组语句。
先处理子查询,再处理父查询。
细分如下:
1
。
简单嵌套查询
查询选修课程号为
'101'
并且成绩高于学生号为
'9501101'
的所有学生的成绩
.
select * from sclass
where cno='101' and degree>=
(select degree from sclass where sno='9501101'and cno='101')
当子查询跟随在
=
、
!=
、
<
、
<=
、
>
、
>=
之后,
子查询的返回值只能是一个,
否则应在外层
where
子句中用
一个
in
限定符
,
即要返回多个值,要用
in
或者
not in
2
。
带
[not] in
的嵌套查询
只要主查询中
列或运算式
是在(不在)子查询所得结果列表中的话,则主查询的结果为我们要的数据
select sales_id,tot_amt
from sales
where sale _id in(select sale_id from employee where sex='F')
where sno not in(Select distinct sno from sclass)
3
。
带
exists
的嵌套查询
子查询的结果至少存在一条数据时,则主查询的结果为我们要的数据。(
exists
)或自查询的结果找不到
数据时,则主查询的结果为我们要的数据
(not exists)
我们经常查询的两个表有多少重复的记录就用这个