天天看點

oracle子查詢

子查詢概念 :當一個查詢的結果是另一個查詢的條件時,稱之為子查詢。

使用子查詢注意事項:

         子查詢可以嵌套多層

         子查詢需要圓括号()括起來

子查詢文法:

SELECT     select_list

FROM       table

WHERE    expr operator

                           (SELECT    select_list

                         FROM                  table);

l  子查詢 (内查詢) 在主查詢之前一次執行完成。

l  子查詢的結果被主查詢使用 (外查詢)。

舉例:查詢員工的工資大于JONES的員工資訊

分析過程如下:

首先:查詢JONES的員工工資是多少 :結果2975

SQL> select sal from emp where ename='JONES';

實際上我們要查詢的是:薪資大于2975的員工的資訊寫法如下:

SQL> select * from emp where sal>2975;

//綜合以上寫出子查詢的結果如下:

SQL> select * from emp where sal>(select sal from emp where ename='JONES');

注意:

l  子查詢要包含在括号内。

l  将子查詢放在比較條件的右側。

根據查詢的結果(内部嵌套查詢的結果)把子查詢的類型分為單行子查詢與多行子查詢,

   注意:

l  單行操作符對應單行子查詢,多行操作符對應多行子查詢。

單行操作符

>、>=、 <、 <= 、<>、=

舉例:

//查詢編号7876相同職位的員工資訊 并且薪資大于編号為7521的薪資的員工資訊

SQL> select * from emp where job=( select job from emp where empno=7876) and sal>( select sal from emp where empno=7521);

//子查詢含有組函數

SQL> select * from emp where sal>(select avg(nvl(sal,0)) from emp);

//子查詢含有having子句查詢部門的最小工資大于20号部門最小工資的部門号及最小工資數

SQL> select deptno,min(sal) from emp group by deptno having min(sal)>( select min(sal) from emp where deptno=20);

備注:子查詢可以傳回空行 沒要查詢到結果是可以的。

多行子查詢

l   傳回多行。

l  使用多行比較操作符。

操作符如下圖:

操作符

描述

In

等于清單中的任何一個

Any

子查詢傳回的任意一個值比較 相同還有some

All

和子查詢傳回的所有值比較  

Exists

//查詢薪水小于工作崗位CLERK的任何一個薪資的員工資訊并且不包含工作崗位為CLERK的員工資訊

SQL> select * from emp where sal < any (select sal from emp where job='CLERK') and job<>'CLERK';

//all與所有值比較 >all 代表的是大于查詢結果的最大值

SQL> select * from emp where sal > all (select sal from emp where job='CLERK') and job<>'CLERK';

//查詢崗位與部門編号為10相同的員工資訊 不包含自己。

SQL> select * from emp where job in(select job from emp where deptno=10) and deptno<>10;

原文:http://blog.csdn.net/java958199586/article/details/7350730