Oracle 数据库的子查询(关联子查询)
文章目錄
- 一、子查詢結果返回一個值(單列單行)
- 二、子查詢結果返回多行(單列多行)
- 三、子查詢結果返回多列多行
- 四、關聯子查詢
- (一)子查詢執行順序
- (二)exists 關鍵字
- 五、子查詢總結
- 六、關聯子查詢示例
一、子查詢結果返回一個值(單列單行)
選擇比較運算符:> < >= <= = <>
select ename from emp_xxx where salary > ( select salary from emp_xxx where ename = '張無忌' ) ;二、子查詢結果返回多行(單列多行)
選擇比較運算符:>ALL >ANY <ALL <ANY in
select ename from emp_xxx where salary > ALL( select salary from emp_xxx where ename = '張無忌' ) ; select ename from emp_xxx where salary > ANY( select salary from emp_xxx where ename = '張無忌' ) ; select ename,salary,job from emp_xxx where deptno in(select deptno from emp_xxx where ename = '劉蒼松') and ename <> '劉蒼松' ;三、子查詢結果返回多列多行
查詢每個部門薪水最高的員工:
select ename, salary, job, deptno from emp_xxx where (deptno, salary) in ( select deptno, max(salary) from emp_xxx where deptno is not null group by deptno ) ;注意:
子查詢的條件是單列還是多列沒關系 , 關鍵是要分清返回的是單行還是多行。
- 如果是單行 , 用單行比較運算符 ,=,>,< 這些
- 如果是多行 , 用 in, >all, >any, <all, <any 這些
四、關聯子查詢
子查詢不再是獨立的 Sql 語句 , 需要依賴主查詢傳來的參數 , 這種方式叫關聯子查詢。
子查詢又稱內部查詢,而包含子查詢的語句稱之外部查詢(又稱主查詢)。
查詢員工表中薪水比所在部門平均薪水小的員工:
select ename, salary, deptno from emp_xxx a where salary < ( select avg(nvl(salary,0)) from emp_xxx where deptno = a.deptno ) ; -- 子查詢不再是獨立的 Sql 語句 , 需要依賴主查詢傳來的參數 a.deptno查詢員工表中薪水比所在部門平均薪水大的員工:
select ename,salary,deptno, (select avg(ifnull(salary,0)) from emp_htlwk where deptno = e.deptno) avgsal from emp_htlwk e where salary > (select avg(ifnull(salary,0)) from emp_htlwk where deptno =e.deptno);上述例子中,一個子查詢嵌到主查詢的 select 子句,一個子查詢嵌到 where 子句中。
(一)子查詢執行順序
-
非關聯子查詢是獨立于外部查詢的子查詢,子查詢總共執行一次,執行完畢后將值傳遞給外部查詢。所以非關聯子查詢,先執行子查詢,再執行主查詢
-
關聯子查詢的執行依賴于外部查詢的數據,外部查詢執行一行,子查詢就執行一次。所以關聯子查詢,先執行主查詢,再執行子查詢
(二)exists 關鍵字
哪些人是其他人的經理(即查詢有下屬的員工):
select ename from emp_xxx a where exists (select 1 from emp_xxx where mgr = a.empno) ;-
exists 關鍵字判斷子查詢有沒有數據返回,有則為 ture,沒有則為 false,exists 不關心子查詢的結果,所以子查詢中 select 后面寫什么都可以,本例中我們寫常量“1”
-
sql 執行順序從主查詢開始 , 把主查詢中的 empno 數據傳入子查詢 , 作為條件中的參數
哪些人不是別人的經理:
select ename from emp_xxx a where not exists (select 1 from emp_xxx where mgr = a.empno) ;哪些部門沒有員工:
select deptno, dname from dept_xxx d where not exists (select 1 from emp_xxx where deptno = d.deptno) ;五、子查詢總結
六、關聯子查詢示例
1.查詢每個科目成績最高的學生信息:
SELECT t.stuid, t.stuname, t.score, t.classid FROM stugrade t WHERE t.score = (SELECT max(tmp.score) FROM stugrade tmp WHERE tmp.classid = t.classid)2.篩選出每個部門工資排名前二的員工信息,并且按部門升序,按部門分組,部門內的員工按工資降序:
select deptid,salary from employee a where 2 > (select count(1)from employee bwhere a.salary < b.salary and a.deptid = b.deptid) order by a.deptid,a.salary desc;總結
以上是生活随笔為你收集整理的Oracle 数据库的子查询(关联子查询)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工口安卓版下载安装(工口安卓版)
- 下一篇: 复制linux系统盘(复制linux)