EXISTS 子句和 JOIN

EXISTS clause and JOIN

查询 1

select ename,deptno 
from emp1 
where exists 
(select deptno from dpt where dpt.deptno=emp1.deptno AND deptno>20);

returns ename对应子查询中deptno字段的条件

查询 2

select ename,deptno 
from emp1 
where exists 
(select deptno from dpt where deptno>20);

但在查询 2 中,结果包含字段 ename 和 deptno 的所有值

两个查询的结果集发生了什么变化?是因为连接吗?连接实际上如何在查询 1 中带来不同的结果集?为什么在查询 1 而不是查询 2 中考虑了 where 条件?

 legends:
 empname is employee name in the table emp,
 deptno is department no. which is the common field in emp and dept tables.

第一个查询是相关子查询:

Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner query has to be executed for every row of outer query.

select ename,deptno 
from emp1 
where exists 
(select deptno from dpt where dpt.deptno=emp1.deptno AND deptno>20);

你可以改写为:

select e.ename, e.deptno 
from emp1 e
join dpt d
  on d.deptno = e.deptno
where d.deptno > 20;

第二个查询(noncorrelated/simple 子查询):

A noncorrelated subquery is subquery that is independent of the outer query and it can executed on its own without relying on main outer query.

select ename,deptno 
from emp1 
where exists 
  (select deptno from dpt where deptno>20);

相当于(如果存在子查询):

select ename,deptno 
from emp1 
where 1 = 1

或者(如果子查询returns没有):

select ename,deptno 
from emp1 
where 1 = 0