SQL Server 中關於EXCEPT和INTERSECT的用法


熟練使用SQL Server中的各種用法會給查詢帶來很多方便。今天就介紹一下EXCEPT和INTERSECT。注意此語法僅在SQL Server 2005及以上版本支持。

EXCEPT是指在第一個集合中存在,但是不存在於第二個集合中的數據。

INTERSECT是指在兩個集合中都存在的數據。

測試如下:

create table t1(id int,mark char(2))
go
create table t2(id int,mark char(2))
go
insert into t1
	select 1,'t1' union all
	select 2,'t2' union all
	select 3,'t3' union all
	select 4,'t4'
go
insert into t2
	select 2,'t2' union all
	select 3,'m3' union all
	select 5,'m5' union all
	select 6,'t6'
go
select * from t1
EXCEPT
select * from t2
go
select * from t1
INTERSECT
select * from t2
go

--EXCEPT結果集為
--1	t1
--3	t3
--4	t4

--INTERSECT結果集為
--2	t2

  

EXCEPT和INTERSECT的優先級:

為了測試它們之間的優先級,運行下面的測試代碼:

create table t3(int id,mark char(2))
go
insert into t3
	select 3,'t3' union all
	select 3,'r3' union all
	select 5,'m5' union all
	select 5,'r5' union all
	select 7,'b7' union all
	select 8,'b8'
go
select * from t1
EXCEPT
select * from t2
INTERSECT
select * from t3

--運行結果
--1	t1
--2	t2
--3	t3
--4	t4

  

為什么會出現如上結果呢,請看下面的執行計划:

ExceptIntersect

 

原來t2和t3先進行的INTERSECT運算,得出5 m5結果集,再和t1進行EXCEPT運算。

 

如需轉載,請注明本文原創自CSDN TJVictor專欄:http://blog.csdn.net/tjvictor

 


免責聲明!

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



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