子查詢語法詳解


子查詢所要解決的問題:不能一步求解的問題!
語法:select 語句的嵌套
1.單行子查詢:如果子查詢只返回一行記錄,就是單行子查詢
單行操作符: = , > , >=,<,<=,<>
2.多行子查詢:如果子查詢返回多行記錄,就是多行子查詢
多行操作符: in(set) , any , all
如:查詢工資比SCOTT高的員工信息,分兩步
1.查詢SCOTT的工資: select sal from emp where ename='SCOTT';
2. 查詢比3000高的員工: select * from emp where sal>3000;
子查詢: select * from emp where sal > (select sal from emp where ename='SCOTT');
//多行子查詢
1.in 在集合中
select * from emp where deptno in (select deptno from dept where dname='SALES'or dname='ACCOUNTNG');
select e.* from emp e,dept d where e.deptno=d.deptnoand (d.dname='SALES' or d.dname='ACCOUNTING');
2.any: 和集合中任意一個值比較
//查詢工資比30號部門任意一個員工高的員工信息
select * from emp where sal > any (select sal from emp where deptno=30);
//大於集合任意一個值,只需要大於集合最小值即可
select * from emp where sal > (select min(sal) from emp where deptno=30)
3. all:和集合中的所有值比較
//查詢工資比30號部門所有員工高的員工信息
select * from emp where sal > all (select sal from emp where deptno=30);
或 select * from emp where sal > (select max(sal) from emp where deptno=30)
注意的問題:
1. 要有括號
2.合理的書寫風格
3.可以在主查詢的where ,select, having ,from后面都可以使用子查詢
select 語句后面使用子查詢,只能使用單行子查詢,即只允許返回一條記錄
4.不可以在group by后面使用子查詢
5.強調from后面的子查詢
6.主查詢和子查詢可以不是同一張表;只要子查詢返回的結果主查詢可以使用 即可
7.一般不在子查詢中排序;但在top-n分析問題中,必須對子查詢排序
8.一般先執行子查詢 再執行主查詢;但相關子查詢例外
9.單行子查詢只能使用單行操作符;多行子查詢只能使用多行操作
主查詢可以有多個子查詢,即1:n關系,子查詢可以嵌套用,最多855層
10.子查詢中的null ,為什么集合中若有空值,不能用not in(10,20,null) 可以用in( );
舉例:和上面序號對應
3. //select 語句后面使用子查詢,只能使用單行子查詢,即只允許返回一條記錄
select empno,ename,sal,(select job from emp where empno=7839) 第四列 from emp;
//按部門分組查詢最低工資,且最低工資大於10號部門的最低工資才顯示
select deptno ,min(sal) from emp group by deptno having min(sal) >
(select min(sal) from emp where deptno = 10);
//查詢員工號,姓名,月薪 ,年薪
select * from (select empno,ename,sal , sal*12 年薪 from emp );
6.查詢部門名稱是sales的員工
select * from emp where deptno = (select deptno from dept where dname='SALES');//子查詢方式
select e.* from emp e,dept d where e.deptno = d.deptno and d.dname='SALES';//多表查詢方式
7.Top-n分析: 找出員工工資表的前三名
8.一般先執行子查詢 再執行主查詢;但相關子查詢例外
9.單行子查詢只能使用單行操作符;多行子查詢只能使用多行操作
//查詢工資最低的員工的職位和薪水
select ename,job,sal from emp where sal =(select min(sal) from emp);
//下面是非法的,因為多行子查詢使用單行比較符
select ename from emp where sal = (select min(sal) from emp groupby deptno);錯誤
10. 單行子查詢空值問題 不能貿然使用 = 或 != ,因為后面返回null就永遠不成立
select ename, job from emp where job=(select job from emp where ename='mike') //子查詢可能返回null ,而判斷是否為空,不能使用 = 或者 !=
多行子查詢中的null:
集合有空值,不能用not in 可以用in
//查詢不是領導的員工
select * from emp where empno not in (select mgr from emp); //錯誤寫法
select * from emp where empno not in (select mgr from emp where mgr is not null);//正確
---------------------
作者:水河澹澹
來源:CSDN
原文:https://blog.csdn.net/qq_33497137/article/details/53791261
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM