集合運算—union(並集)、intersect(交集)和except(差集)


一、集合運算的基本格式是:

集合查詢1

<集合運算>

集合查詢2

[order by ...]

二、集合運算符是對兩個集合操作的,兩個集合必須具有相同的列數,列具有相同的數據類型(至少能隱式轉換的),最終輸出的集合的列名由第一個集合的列名來確定。(可以用來連接多個結果);集合運算對行進行比較時,認為兩個NULL值相等。

三、union和union all(並集)集合運算

union(並集)集合運算可以將多個查詢結果集合並成一個結果集。union(隱含distinct,去除重復)、union all。

--UNION合並兩個查詢結果集,並且將其中完全重復的數據行合並為一條
select tName,tSex from teacher 
union
select sName,sSex from student
--UNION ALL合並兩個查詢結果集,返回所有數據,不會去掉重復的數據
select tName,tSex from teacher 
union all
select sName,sSex from student

Union因為要進行重復值掃描,所以效率低,因此如果不是確定要合並重復行,那么就用UNION ALL

四、intersect(交集)集合運算:刪除兩個集合中的重復行,返回只有在兩個集合中都出現的行

--先將其中完全重復的數據行刪除,再對兩個查詢結果集取其交集
select tName,tSex from teacher 
intersect
select sName,sSex from student

ANSI SQL 支持帶有all選項的intersect集合運算,但SQL Server 2008現在還不支持all選項。要想查詢交集中的所有數據的辦法:

with intersect_all as
(
    select row_number() over(partition by tName,tSex order by (select 0)) as rowNum,
        tName,tSex from teacher
    intersect
    select row_number() over(partition by sName,sSex order by (select 0)) as rowNum,
        sName,sSex from student
)
select tName,tSex from intersect_all

--備注:在排序函數的over子句中使用order by (select <常量>)用這種方法可以告訴SQL Server不必在意行的順序

五、except(差集)集合運算:先將其中完全重復的數據行刪除,再返回只在第一個集合中出現,在第二個集合中不出現的所有行。

select tName,tSex from teacher 
except
select sName,sSex from student

ANSI SQL 支持帶有all選項的except集合運算,但SQL Server 2008現在還不支持all選項。要想查詢交集中的所有數據的辦法:

with except_all as
(
    select row_number() over(partition by tName,tSex order by (select 0)) as rowNum,
        tName,tSex from teacher
    except
    select row_number() over(partition by sName,sSex order by (select 0)) as rowNum,
        sName,sSex from student
)
select tName,tSex from except_all

--備注:在排序函數的over子句中使用order by (select <常量>)用這種方法可以告訴SQL Server不必在意行的順序

六、集合運算的優先級:intersect運算比union和except運算的優先級高,而union和except的優先級相等

 


免責聲明!

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



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