1. 程式人生 > >關聯子查詢+巢狀子查詢

關聯子查詢+巢狀子查詢

關聯子查詢
定義
1引用外部的一列或多列
2將外部查詢的每一行都傳遞給子查詢,子查詢依次讀取傳遞過來的每一行的值,並將其使用到子查詢上,直到外部查詢的所有行都處理完為止,然後返回子查詢的結果

獲取員工工資低於所在部門的平均工資的員工資訊
select empno,ename,sal,deptno from emp out
where sal <(
select avg(sal) from emp inner
where inner.deptno=out.deptno
)
這裡寫圖片描述

上面等價於

select  out.empno,out.ename,out.sal,out
.deptno from emp out, ( select avg(sal) avgSal ,deptno from emp group by deptno ) inner where inner.deptno=out.deptno and out.sal<inner.avgSal

這裡寫圖片描述

解釋
1外部查詢(select empno,ename,sal,deptno from emp)的的每一行記錄傳遞給子查詢
(select avg(sal) from emp inner
where inner.deptno=out.deptno)
2.子查詢讀取讀取外部傳過來的值,最後返回部門平均工資的列(隱藏分組deptno)

簡單的理解就是:

select out.empno,out.ename,out.sal,out.deptno from emp out,
(
select avg(sal) avgSal ,deptno from emp
group by deptno
) inner
where inner.deptno=out.deptno
and out.sal< inner.avgSal
out表關聯inner表,在獲取小於平均工資的員工

exists在關聯子查詢的使用

獲取80年的員工號資訊
select empno,ename,sal,hiredate,substr(hiredate,8,2)
from emp out where exists(
select empno from emp inner
where out.empno=inner.empno
and substr(hiredate,8,2)=’80’);

select empno,ename,sal,hiredate,substr(hiredate,8,2)
from emp out where exists(
select 1 from emp inner
where out.empno=inner.empno
and substr(hiredate,8,2)=’80’);

這裡寫圖片描述

巢狀子查詢
子查詢內部巢狀子查詢,巢狀子查詢層數最大255層

根據工作地點在'NEW YORK','CHICAGO'的2個部門,根據2個部門平均工資的最大值,獲取工資大於這個最大值的員工資訊
select empno,ename,ename,sal,deptno from emp
where sal>(
            select  max (avg(sal)) from emp where deptno in
                    (
                    select deptno from dept
                    where loc in ('NEW YORK','CHICAGO')
                    )
            group by deptno
          );

這裡寫圖片描述

解釋
1 (
select deptno from dept
where loc in (‘NEW YORK’,’CHICAGO’)
)
獲取工作地點在’NEW YORK’,’CHICAGO’的2個部門

2select max (avg(sal)) from emp where deptno in
(部門集合 )
group by deptno
獲取 部門的平均工資,在獲取平均工資的最大值