Oracle的多表查詢------- 子查詢

/*

   語法:

      select * from tab1 where ( 子查詢  )

     

       select * from (子查詢)

      

   子查詢作用:

      1)可以作爲另一個查詢的條件

      2)可以作爲一張表

     

    子查詢類型:

      1)單行子查詢(子查詢返回的結果是一條)

      2)多行子查詢(子查詢返回的結果是多條)

*/

-- 需求:查詢工資比編號7521高的員工

-- 1)查詢編號7521的員工工資

select sal from emp where empno = 7521;

 

-- 2) 把上面的查詢結果作爲一個條件,  查詢工資比編號7521高的員工

select *

from emp

where sal > (select sal from emp where empno = 7521);

 

-- 需求:查詢出比僱員 7654 的工資高,同時從事和 7788 的工作一樣的員工

-- 1)查詢僱員 7654 的工資

select sal from emp where empno = 7654;

 

--2)查詢7788員工的工作

select job from emp where empno = 7788;

 

--3)把上面兩個查詢結果,作爲條件

select *

from emp

where sal > (select sal from emp where empno = 7654)

and job = (select job from emp where empno = 7788);

 

 

-- 需求:要求查詢每個部門的最低工資和最低工資的僱員和部門名稱

-- 1)查詢每個部門的最低工資

select deptno,min(sal) as minsal

from emp

groupby deptno;

 

-- 2)把上面查詢結果作爲一張表

select *

from emp e,dept d,

(select deptno,min(sal) as minsal

from emp

groupby deptno) dminsal

where dminsal.deptno = d.deptno

and e.sal = dminsal.minsal;

 

 

-- 子查詢空值問題

-- 需求:查詢不是老闆的員工

-- 1)查詢所有老闆的編號

selectdistinct mgr from emp;

 

-- 2)把上面的查詢作爲條件

-- 這時發現這個查詢查不到數據,因爲子查詢返回null

-- 注意:子查詢一旦返回null值,主查詢查詢沒有結果的

select *

from emp

where empno notin (selectdistinct mgr from emp where mgr isnotnull);

 

-- 非法子查詢用法

-- 子查詢返回多個結果,但是不能在主查詢使用單個條件判斷

select *

from emp

where job = (select job from emp);

 

 

select * from emp;

select * from dept;



---=========exists用法

/*

  語法:

     select * from tab1 whereexists (sql查詢語句)

    

     sql查詢語句:

       1)查詢返回結果不爲null,那麼exists結果爲true

       2)查詢返回結果爲null,那麼exists結果爲false

*/

-- true

select * from emp whereexists (select * from emp where empno = 7369);

-- 上面語句等價於(恆等)

select * from emp where1=1;

 

-- false

select * from emp whereexists (select * from emp where empno = 88888);

-- 上面語句等價於

select * from emp where1=2;

 

-- 需求:查詢有員工的部門

select * from dept d whereexists ( select * from emp e where e.deptno =d.deptno  );

 

 

 

 

 

 

select * from emp;

 

select * from dept;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章