1. 程式人生 > >Oracle【子查詢】

Oracle【子查詢】

只有一個 一次 oracle子查詢 註意 需要 rac class 存在 pre

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

 1 --查詢所有比雇員‘CLARK‘工資高於員工的信息
 2 select * from emp where sal>(select sal from emp where ename=CLARK);
 3 --查詢工資高於平均工資的員工的名字和工資
 4 select ename,sal from
emp where sal>(select avg(sal) from emp); 5 --查詢和soctt屬於同一部門且工資比他低的員工資料 6 select * from emp where deptno=(select deptno from emp where ename=SCOTT) and sal<(select sal from emp where ename=SCOTT); 7 --查詢工資最高的員工資料 8 select * from emp where sal=(select max(sal) from emp); 9 --查詢職務和SCOTT相同,雇傭時間早的員工信息
10 select * from emp where job=(select job from emp where ename=SCOTT) and hiredate < (select hiredate from emp where ename=SCOTT); 11 --查詢工資比SCOTT高或者雇傭時間早的員工編號和姓名 12 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 子查詢語句

1 --查詢工資高於任意一個CLERK的所有員工信息
2 select * from emp where sal> any (select sal from emp where job=CLERK);
3 --查詢工資高於所有的SALESMAN的員工信息
4 select * from emp where sal> all (select sal from emp where job=SALESMAN);
5 --查詢部門20中同部門10的雇員工作一樣的雇員信息
6 select * from emp where job  in (select job from emp where deptno=10) and deptno=20;

Oracle【子查詢】