核心SQL
SELECT empno,ename,job
FROM emp outer
WHERE exists
(
SELECT ‘X’ FROM emp WHERE mgr = outer.empno
);
EXISTS关心的是在子查询里能否找到一个行值(哪怕有10行匹配,只要找到一行就行),如果子查询有行值,则立即停止子查询的搜索,然后染回罗技标识TRUE,若果子查询没有返回行值,则返回逻辑标识FALSE,子查询要么返回T,要么返回F,以此决定了朱查询的调用行的去留,然后住查询指针指向下一行,继续调用子查询。
对于关联子查询,在某种特定的条件下,比如子查询表是个大表,使用in不如exists效率高,Oracle推荐使用exists()代替in。
以SCOTT用户下emp为例
scott@ORCL>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 1000 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
SELECT empno,ename,job
FROM emp outer
WHERE exists
(
SELECT 'X' FROM emp WHERE mgr = outer.empno
6 );
EMPNO ENAME JOB
---------- ---------- ---------
7566 JONES MANAGER
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7902 FORD ANALYST
6 rows selected.