SQL差集的使用(EXCEPT)

前言

一般來說,我們大多是用交集,但如果要取差集呢? 如下圖A + C部份!

image

實作

直覺來想的話,會使用NOT IN OR NOT EXISTS來做,但是也可以使用EXCEPT哦!

請參考以下的SQL, 在ORACLE的話,請使用MINUS

	--SQL差集練習

--資料準備

DECLARE @EMPLOYEE TABLE

(

ID INT IDENTITY(1,1) 

, EMP_NAME NVARCHAR(32)

, TOOL_NAME NVARCHAR(64)

);



INSERT INTO @EMPLOYEE(EMP_NAME, TOOL_NAME) VALUES(N'打死釘', N'手鎗');

INSERT INTO @EMPLOYEE(EMP_NAME, TOOL_NAME) VALUES(N'打死釘', N'直昇機');



INSERT INTO @EMPLOYEE(EMP_NAME, TOOL_NAME) VALUES(N'亂馬客', N'直昇機');

INSERT INTO @EMPLOYEE(EMP_NAME, TOOL_NAME) VALUES(N'亂馬客', N'炸彈');



--EMP的TOOL_NAME INFO

SELECT * FROM @EMPLOYEE WHERE EMP_NAME = N'亂馬客'

SELECT * FROM @EMPLOYEE WHERE EMP_NAME = N'打死釘'



--亂馬客有,但打死釘沒有的TOOL(圖C)

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'亂馬客'

EXCEPT

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'打死釘'



--打死釘有,但亂馬客沒有的TOOL(圖A)

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'打死釘'

EXCEPT

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'亂馬客'



--亂馬客及打死釘相異的的TOOL(圖A + C)

(SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'亂馬客'

EXCEPT

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'打死釘')

UNION

(SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'打死釘'

EXCEPT

SELECT TOOL_NAME FROM @EMPLOYEE WHERE EMP_NAME = N'亂馬客')
	image 

參考資料

SQL各類集合(差集、交集、聯集等範例)

Oracle UNION, INTERSECT, MINUS OPERATORS AND SORTING QUERY RESULT

你可能感兴趣的:(sql)