SQL多表查詢語句

帶【in】的嵌套查詢

select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal in (select sal from scott.emp where ename='WARD');

上述語句完成的是查詢薪水和WARD相等的員工,也可以使用【not in】來進行查詢。

 


帶【any】的嵌套查詢

 

select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal >any(select sal from scott.emp where job='MANAGER');

帶any的查詢過程等價於兩步的執行過程。
(1)執行“select sal from scott.emp where job='MANAGER'”]

(2)查詢到3個薪水值2975、2850和2450,父查詢執行下列語句。

select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal >2975 or sal>2850 or sal>2450;

 


帶【some】的嵌套查詢

 

select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal =some(select sal from scott.emp where job='MANAGER');

帶some的嵌套查詢與any的步驟相同。
(1)子查詢,執行“select sal from scott.emp where job='MANAGER'”

(2)父查詢執行下列語句。
select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal =2975 or sal=2850 or sal=2450;

帶【any】的嵌套查詢和【some】的嵌套查詢功能是一樣的。早期的SQL僅僅允
許使用【any】,後來的版本爲了和英語的【any】相區分,引入了【some】,同時還保留了【any】
關鍵詞。

 


 帶【all】的嵌套查詢

 

select  emp.empno,emp.ename,emp.job,emp.sal  
from scott.emp
where sal >all(select sal from scott.emp where job='MANAGER');

帶all的嵌套查詢與【some】的步驟相同

select  emp.empno,emp.ename,emp.job,emp.sal 
from scott.emp
where sal >2975 and sal>2850 and sal>2450;

 

 


 

並操作的嵌套查詢
並操作就是集合中並集的概念。屬於集合A或集合B的元素總和就是並集。

(select deptno from scott.emp)
union
(select deptno from scott.dept); 

 交操作的嵌套查詢
交操作就是集合中交集的概念。屬於集合A且屬於集合B的元素總和就是交集

(select deptno from scott.emp)
intersect
(select deptno from scott.dept);

差操作的嵌套查詢
差操作就是集合中差集的概念。屬於集合A且不屬於集合B的元素總和就是差集

(select deptno from scott.dept)
minus
(select deptno from scott.emp);

並、交和差操作的嵌套查詢要求屬性具有相同的定義,包括類型和取值範圍

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