1,wherer:子查詢一般會返回單行單列 單行多列 多行單列 ;
2,having:子查詢會返回單行單列,同時表示要使用統計函數;
3,from:子查詢返回多行多列數據(表結構);
4,select:返回單行單列 (一般不使用);
where(進行數據行的篩選操作):
- a:查詢出低于公司平均工資的雇員信息。
select * from emp where sal<(select avg(sal) from emp);
以上的查詢返回單行單列可以作為where子句的過濾條件使用;
- b:查詢公司最早雇傭的雇員的信息。
select * from emp where hiredate= (select MIN(hiredate) from emp);
- C:查詢與scott從事同一工作并且工資相同的雇員信息。
select* from emp
where (job,sal) =( select job,sal
from emp
where ename ='scott') and ename <>'scott';
in:指的是與子查詢返回的內容相同。
select * from emp where sal in (select sal from emp where job = 'manager');
not in:
select* from emp where sal not in(select sal from emp where job='manager')
子查詢中不能有空。
any:
select* from emp where sal = any(select sal from emp where job='manager');
select* from emp where sal > any(select sal from emp where job='manager');
比子查詢的返回的最大值要大
select* from emp where sal < any(select sal from emp where job='manager');
比子查詢返回的最大值要小
all:
<all :比子查詢的返回的最小值要小
>all :比子查詢的返回的最大值要大
where子查詢的幾率很高;
having:
- 查詢出高于公司平均工資的職位名稱 職位人數 平均工資。
select job,count(empno),avg(sal) from emp group by job
having avg(sal)>(select avg(sal) from emp);
select(一般不用):
查詢每個雇員的編號姓名 職位 部門名稱。
select e.empno,e.ename,e.job,
(select d.dname from dept d whered.deptno=e.deptno)from emp e;
(1+n) 次查詢;
from(重點):
- 查詢出每個部門的名稱 位置 部門人數。
select d.dname,d.loc,count(e.empno)
from emp e,dept d
where e.deptno(+)=d.deptno
group by d.dname,d.loc;
(多表查詢)
分步1:select d.deptno,d.dname,d.locfrom dept d;
分步2:select deptno,count(empno)from emp group by deptno;
正確的查詢:
select d.deptno,d.dname,d.loc,temp.count
from dept d,(select deptno,count(empno) count from emp
group by deptno) temp
where d.deptno=temp.deptno(+);
- 多表查詢和子查詢都能實現統計,那么那種方式更好呢?
答:在實際的工作當中,子查詢的主要目地是解決多表查詢的性能問題,所以在開發中使用的是 最多的。最大作用是解決多表查詢帶來的笛卡爾積影響性能的問題。
復雜查詢= 簡單查詢+限定查詢+ 多表查詢+ 分組統計查詢 +子查詢;