SQL函数Intersect,except整理
阅读原文时间:2023年09月27日阅读:1

1、  集合函数使用的规则

①   每个集合要求列数量相同,列顺序相同。

②   每个集合显示的列,要求数据类型一致或者可隐式转换成同一数据类型

③   最终集合列名称与第一个集合的列名称一致

2、  各集合函数说明

①   Intersect操作符,显示结果集的交集,按第一列排序

②   except操作符,显示第一个结果集减去第二个结果集的记录,按第一列排序

3、  数据准备:

①     创建表test_A,test_B

create table test_A ( id SMALLINT, name varchar(10) );
create table test_B ( id SMALLINT, name varchar(10) );

②     准备数据

insert into test_A values(0,'张三');

insert into test_A values(4,'李四');

insert into test_A values(2,'王五');

insert into test_A values(6,'马六');

insert into test_B values(null,null);

insert into test_B values(4,'李四');

insert into test_B values(0,'周八');

insert into test_B values(2,'王五');

3、 函数效果展示:

select id,name from test_A
Intersect
select id,name from test_B
---test_A与test_B的交集,并按第一列排序

select id,name from test_A
except
select id,name from test_B
--test_A减去(test_A与test_B的交集),并按第一列排序

4、 except函数执行计划中-有排序步骤

select id,name from test_A
except
select id,name from test_B
--test_A减去(test_A与test_B的交集),并按第一列排序