數據庫學習(十二)

子查詢:也是實現多表查詢的,在子查詢中可以包含in any all 等關鍵字,也可以包含比較運算符等。子查詢靈活多變。子查詢經常出現的如下兩個位置:

(1)where子句中的子查詢

查詢結果爲單行單列的子查詢
--》查詢員工表中的工資比smith還要高的全部員工信息
select * from t_employee where sal>(select sal from t_wmployee where ename='smith');

查詢結果爲單行多列的子查詢

-->查詢員工表中工資和職位與smith一樣的全部員工信息。
select * from t_employee where (sal,job)=(select sal,job from t_employee where ename='smith');
查詢結果爲多行單列的子查詢
使用帶關鍵字in的子查詢
--》查詢員工表中的數據,這些數據的部門號必須在部門表t_dept表中。
select * from t_employee where deptno in(select deptno from t_dept);

使用帶關鍵字any的子查詢
=any    功能和關鍵字in一樣
>any  >=    比子查詢返回的數據中最小的還要大的數據
<any   <=    比子查詢返回的數據中最大的還要小
--》查詢員工表姓名和工資,這些員工的工資不低於職位manager的工資
先查詢員工表中職位爲manager的工資
select sal from t_employee where job='manager';

select ename,sal from t_employee where sal>any(select sal from t_employee where job ='manager');


使用帶有關鍵字all的子查詢
>all    >=all    比子查詢返回的結果最大的還要大於的數據

<all    <=all    比子查詢返回的結果最小的還要小於的數據

--》查詢員工的姓名和工資,這些員工的工資高於職位爲manager的工資
select ename,sal from t_employee where sal>all(select sal from t_employee where job='manager');

from 子句中的子查詢
特點:當子查詢的返回結果是多行多列的時候,該子查詢語句一般會在主查詢語句from子句後邊,子查詢的結果被當做一張臨時表的方式來處理

查詢結果爲多行多列的子查詢
--》查詢員工表中各部門的部門號,部門名稱,部門地址,員工的人數,員工的平均工資。
select d.deptno,d.name,d.loc,count(e.ename),avg(e.sal) from t_employee e inner join t_dept d on e.deptno=d.deptno group by e.deptno;

子查詢的方式完成
select d.deptno,d.dname,d.loc,num,average from t_dept d inner join (select deptno dno,count(ename) num,avg(sal) average from t_employee group by deptno) e on d.deptno=e.dno;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章