关于SQL中的Except
1 use test1 2 select address_district,COUNT(address_district) as total from hr_personal_test group by address_district with rollup; 3 create table test1 (id int); 4 create table test2 (num int); 5 6 --1 1(1,2,3) 2(1,4) 7 --insert into test1 select 1 union select 2 union select 3 8 --insert into test2 select 1 union select 4 9 10 --select id from test1 except select num from test2;-------返回结果2,3 11 12 13 delete from test1 ; 14 delete from test2; 15 --2 1(1,2) 2(1,2,3,4) 16 --insert into test1 select 1 union select 2 17 --insert into test2 select 1 union select 2 union select 3 union select 4 18 --select id from test1 except select num from test2; --------返回结果 没有 19 20 delete from test1 ; 21 delete from test2; 22 --3 1(1,2) 2(3,4) 23 insert into test1 select 1 union select 2 24 insert into test2 select 3 union select 4 25 select id from test1 except select num from test2-------- 返回结果 1,2 26 27 delete from test1 ; 28 delete from test2; 29 --4 1(1,2,3) 2(1,2) 30 insert into test1 select 1 union select 2 union select 3 31 insert into test2 select 1 union select 2 32 select id from test1 except select num from test2--------返回结果3
create table test1(id int ,name nvarchar(20)) create table test2(id int ,post nvarchar(4)) insert into test1 (name) values (‘a‘),(‘b‘),(‘b‘),(‘c‘) insert into test2 (post) values(‘a‘) select name from test1 except select post from test2--------返回 b,c select name from test1 where name not in(select post from test2)---------返回 b,b,c
由此可以得出以下几点:
1、Except运算符对比的是数据,而非按照不同表中相同字段名的字段。
2、Except运算符简而言之:查找左边表中不在右边表中存在的数据。用集合来表示应该是 A-A交B 而非 (A并B)-(A交B)。
3、Except运算符会去重,而not in 不会。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。