SELECT emp.empno,emp.ename,emp.job,emp.sal FROM scott.emp
WHERE sal>any(SELECT sal FROM scott.emp WHERE job='MANAGER');
--上面的意思只要sal>子查询里面返回最小的一个sal值。
--分解出来看看如下:
SELECT sal FROM scott.emp WHERE job='MANAGER';
SELECT emp.empno,emp.ename,emp.job,emp.sal FROM scott.emp
WHERE sal>2975 OR sal>2850 OR sal>2450;
--结果:
EMPNO ENAME JOB SAL
---------- -------------------- ------------------ ----------
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
SAL
----------
2975
2850
2450
EMPNO ENAME JOB SAL
---------- -------------------- ------------------ ----------
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
另:SELECT emp.empno,emp.ename,emp.job,emp.sal FROM scott.emp
WHERE sal>any(SELECT sal FROM scott.emp WHERE job='MANAGER');
等同于语句:
SELECT emp.empno,emp.ename,emp.job,emp.sal FROM scott.emp
WHERE sal>SOME(SELECT sal FROM scott.emp WHERE job='MANAGER');
下面来看ALL的使用:
SELECT emp.empno,emp.ename,emp.job,emp.sal FROM scott.emp
WHERE sal>ALL(SELECT sal FROM scott.emp WHERE job='MANAGER');
--结果:
EMPNO ENAME JOB SAL
---------- -------------------- ------------------ ----------
7788 SCOTT ANALYST 3000
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
理解了any和some,去理解ALL,很容易了,当我们WHERE 条件中sal>ALL(...)
表示sal必须大于子查询中返回最大的sal值。
只要我们注意一下,就不难发现ALL于ANY(SOME),在上面的例子中反义。
交操作的嵌套查询
交操作就是集合中交集的概念。
(SELECT deptno FROM scott.emp)
INTERSECT
(SELECT deptno FROM scott.dept);
--结果:
DEPTNO
----------
10
20
30
差操作的嵌套查询
差操作就是集合中差集的概念。(我好久没有理解这差集,现在都忘记了,来记录一下)
属于集合A且不属于集合B的元素总和就是差集。
(SELECT deptno FROM scott.dept)
MINUS
(SELECT deptno FROM scott.emp);
--结果:
DEPTNO
----------
40
--从MS SQL上理解可以相当于语句:
SELECT scott.dept.deptno FROM scott.dept
LEFT OUTER JOIN scott.emp ON scott.emp.deptno=scott.dept.deptno WHERE scott.emp.deptno IS NULL;
--或者:
SELECT scott.dept.deptno FROM scott.dept
LEFT JOIN scott.emp ON scott.emp.deptno=scott.dept.deptno WHERE scott.emp.deptno IS NULL;
--结果:
DEPTNO
----------
40
转自:http://www.cnblogs.com/wghao/archive/2007/10/16/925645.html