Oracle【子查詢】

Oracle子查詢:當一個查詢依賴於另一個查詢的結果的時候,就須要使用子查詢。
單行子查詢 :
篩選條件不明確,須要執行一次查詢且查詢結果只有一個字段且字段值只有一個。
注意:where子句中容許出現查詢語句,該查詢語句稱爲子查詢。
使用:select 內容 from 表名 where 字段名 比較運算符 子查詢語句
sql

--查詢全部比僱員'CLARK'工資高於員工的信息
select * from emp where sal>(select sal from emp where ename='CLARK');
--查詢工資高於平均工資的員工的名字和工資
select ename,sal from emp where sal>(select avg(sal) from emp);
--查詢和soctt屬於同一部門且工資比他低的員工資料
select * from emp where deptno=(select deptno from emp where ename='SCOTT') and sal<(select sal from emp where ename='SCOTT');
--查詢工資最高的員工資料
select * from emp where sal=(select max(sal) from emp);
--查詢職務和SCOTT相同,僱傭時間早的員工信息
select * from emp where job=(select job from emp where ename='SCOTT') and hiredate < (select hiredate from emp where ename='SCOTT');
--查詢工資比SCOTT高或者僱傭時間早的員工編號和姓名
select empno,ename from emp where sal>(select sal from emp where ename='SCOTT') or hiredate < (select hiredate from emp where ename='SCOTT');

多行子查詢:
子查詢的結果只有一個字段可是字段有n個值,考慮使用多行子查詢,其實使用關鍵字

關鍵字1:any 任意
  select 內容 from 表名 where 字段名 比較運算符 any 子查詢語句
關鍵字2:all 全部
  select 內容 from 表名 where 字段名 比較運算符 all 子查詢語句
關鍵字3:in 表示任意存在,至關於 = any 
  select 內容 from 表名 where 字段名 in 子查詢語句 
  select 內容 from 表名 where 字段名 not in 子查詢語句
spa

--查詢工資高於任意一個CLERK的全部員工信息
select * from emp where sal> any (select sal from emp where job='CLERK');
--查詢工資高於全部的SALESMAN的員工信息
select * from emp where sal> all (select sal from emp where job='SALESMAN');
--查詢部門20中同部門10的僱員工做同樣的僱員信息
select * from emp where job  in (select job from emp where deptno=10) and deptno=20;
相關文章
相關標籤/搜索