SQL差集的使用 EXCEPT

2021-09-06 08:09:24 字數 1633 閱讀 2822

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

直覺來想的話,會使用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'亂馬客')

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

oracle union, intersect, minus operators and sorting query result

並集 交集 差集 Sql總結

1.並集 將查詢出的兩個結果合併成乙個結果集 union 去重,合併後的結果都是唯一 union all不去重,合併後的結果有可能出現重複的 oracle mysql sql server都支援下面的並集查詢 select classid from student union select clas...

SQL中EXCEPT和Not in的區別?

except會去重複,not in 不會 除非你在select中顯式指定 except用於比較的列是所有列,除非寫子查詢限制列,not in 沒有這種情況 表tb2中如果有null值的話,not in查詢得不到值 如 a b 表tb1中如果有null值,not in不會查詢出這個null值 如 d ...

SQL中EXCEPT和Not in的區別

初始化兩張表 create table tb1 id int insert tb1 select null union all select null union all select null union all select 1 union all select 2 union all sele...