1. 程式人生 > >oracle 子查詢

oracle 子查詢

哪些 nvl 操作 最大值 rom 區別 1=1 group 多列


6-1:子查詢簡介
6-2:
select * from scott.emp
where sal=(select MIN(sal) from scott.emp);
範例:查找出公司雇傭最早的雇員;
select min(hiredate) from scott.emp
以上查詢會返回單行單列的數據,所有可以直接在where語句中使用.
select * from scott.emp
where hiredate=(select min(hiredate) from scott.emp);
6.1.2、子查詢返回單行多列;
範例:查詢出與scott工資相同,職位相同的所有雇員信息。

select * from scott.emp where (sal,job)=(select sal,job from scott.emp where ename=‘SCOTT‘);

6.1.2.1: 找出部門10中所有經理和部門20中的所有辦事員的詳細資料
   select * from emp where (deptno=10 and job=upper(‘manager‘)) or (deptno=20 and job=upper(‘clerk ‘));
找出不收取傭金或收取的傭金低於100的雇員
   select * from emp where nvl(comm,0)<100;
找出各月最後一天受雇的所有雇員
select * from emp where hiredate= last_day(hiredate);
顯示不帶有‘R‘的雇員姓名
Select ename from emp where ename not like ‘%R%’;

6.1.3 子查詢返回多行單列(重點)
在where字句裏面提供有主要的三個運算符:IN、ANY、ALL。

1:IN操作;
IN操作指的是內容可以在指定的範圍之中存在,
1.1:select sal from scott.emp where job=‘MANAGER’;
2975
2850
2450
1.2:select * from scott.emp
WHERE (sal,job)=(
select sal,job FROM scott.emp where ename=‘SCOTT‘);

多行單列就相當於給出了一個查詢範圍;
對於IN操作還可以使用not IN 進行;
select * from scott.emp
where sal NOT IN (select sal from scott.emp where job=‘MANAGER’);
select ename,sal from scott.emp where sal >(select sal from scott.emp where ename=‘BLAKE‘);
2:ANY操作實際上有三種語法:
1:=ANY:功能上與IN完全是沒有任何區別;
select * from scott.emp
where sal =ANY (select sal from scott.emp where job=‘MANAGER’);
2:>ANY:比子查詢返回的最小的內容要大
select * from scott.emp
where sal >ANY (select sal from scott.emp where job=‘MANAGER’);
3:<ANY:比子查詢返回的最大的值要小
select * from scott.emp
where sal <ANY (select sal from scott.emp where job=‘MANAGER’);
3:ALL操作
ALL兩種操作
1:>ALL: 比子查詢返回的最大值要大
select * from scott.emp
where sal >ALL (select * from scott.emp where job=‘MANAGER’);
2:<ALL: 比子查詢的返回最小的值要小
select * from scott.emp
where sal <ALL (select * from scott.emp where job=‘MANAGER’);
4:EXISTS()判斷
範例:觀察exists()操作
select * from scott.emp
where exists(select * from scott.emp where deptno=99);
因為此時的查詢沒有返回任何的數據行買,所以exists()就認為數據不存在,外部查詢無法查詢出我內容。
範例:觀察exists()操作
select * from scott.emp
where exists(select * from scott.emp where empno=7839);
範例:觀察exists()操作
select * from scott.emp
where exists (select ‘hello’ from dual where 1=1);
範例:使用not exists()
select * from scott.emp
where not exists (select ‘hello’ from dual where 1=2);
6-3:使用HAVING字句查詢;
範例:要求統計出高於公司平均工資的部門編號、平均工資、部門人數。
第一步:根據部門編號分組,統計出每個部門編號的平均工資、部門人數。
select deptno,count(*),avg(sal)
from scott.emp
group by deptno;
第二步:如果要想知道哪些部門的工資高於公司的平均工資,則應該scott.emp表統計查詢
select avg(sal) from scott.emp;
第三步:統計函數
select deptno,count(*),avg(sal)
from scott.emp
group by deptno
having avg(sal)>(select avg(sal) from scott.emp);
6-4:select 子句使用子查詢
首先需要明確的是,這樣的操作意義不大,而且性能不高;
範例:查詢每個雇員的編號,姓名,職位,部門名稱;
select e.empno,e.ename,e.job,d.dname
from scott.emp e,soctt.emp d
where e.deptno=d.deptno;

oracle 子查詢