1.应用
例:
emp表:
Address | Number |
bj | 40 |
bj | 30 |
fj | 20 |
fj | 10 |
dept表:
Bearing | Adds |
NO | bj |
SO | fj |
(1) exists()的应用
select sum(Number) from emp
where exists(
select * from dept where Bearing = 'SO'
)
输出的结果是: 100
结果好像不符合。但答案是正确的,因为:exists是用来判断是否存在的,当exists(查询)中的查询存在结果时则返回真 ,否则返回假。not exists则相反。
exists做为where 条件时,是先对where 前的主查询进行查询,然后用主查询的结果代入exists的查询进行判断 ,如果为真则输出当前主查询的结果 ,否则不输出。
not exists以exists相反。
(2) in的应用
select sum(Number) from emp
where Address in(
select Adds from dept where Bearing = 'SO'
)
输出的结果是: 30
in是用来判断某个字段包含的值。允许在where字句中有多个值。
not in 是不包含的值。
语法:
select * from 表1 where 字段1 in (val,val,.....)
select * from emp
where adds not in(
select Adds from dept where Bearing = 'SO'
);
select * from emp
where not exists(
select Adds from dept
where Bearing ='SO' and emp.Address = dept.Adds
)
2.效率
in和exists的效率值不是绝对的。
in适合于外表大内表小的
select * from emp where deptid in (select id from dept)
转化为:
select * from emp ,(select distinct id from dept) dept
where emp .deptid = dept.id;
exists适合于外表小内表大的
select * from emp where exists(select id from dept where dept.id = emp.deptid )
转化为:
for deptid in (select * from emp )
loop
if (exists(select id from dept where id = emp.deptid )
then
OUTPUT THE RECORD!
end if
end loop