码迷,mamicode.com
首页 > 数据库 > 详细

关于SQL中的Except

时间:2015-04-13 14:16:52      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

 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 不会。

关于SQL中的Except

标签:

原文地址:http://www.cnblogs.com/promiseABetterFutrue/p/4421886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!