集合运算—union(并集)、intersect(交集)和except(差集)

一、集合运算的基本格式是:

集合查询1

<集合运算>

集合查询2

[order by ...]

二、集合运算符是对两个集合操作的,两个集合必须具有相同的列数,列具有相同的数据类型(至少能隐式转换的),最终输出的集合的列名由第一个集合的列名来确定。(可以用来连接多个结果);集合运算对行进行比较时,认为两个NULL值相等。

三、union和union all(并集)集合运算

union(并集)集合运算可以将多个查询结果集合并成一个结果集。union(隐含distinct,去除重复)、union all。

--UNION合并两个查询结果集,并且将其中完全重复的数据行合并为一条
select tName,tSex from teacher 
union
select sName,sSex from student
--UNION ALL合并两个查询结果集,返回所有数据,不会去掉重复的数据
select tName,tSex from teacher 
union all
select sName,sSex from student

Union因为要进行重复值扫描,所以效率低,因此如果不是确定要合并重复行,那么就用UNION ALL

四、intersect(交集)集合运算:删除两个集合中的重复行,返回只有在两个集合中都出现的行

--先将其中完全重复的数据行删除,再对两个查询结果集取其交集
select tName,tSex from teacher 
intersect
select sName,sSex from student

ANSI SQL 支持带有all选项的intersect集合运算,但SQL Server 2008现在还不支持all选项。要想查询交集中的所有数据的办法:

with intersect_all as
(
    select row_number() over(partition by tName,tSex order by (select 0)) as rowNum,
        tName,tSex from teacher
    intersect
    select row_number() over(partition by sName,sSex order by (select 0)) as rowNum,
        sName,sSex from student
)
select tName,tSex from intersect_all

--备注:在排序函数的over子句中使用order by (select <常量>)用这种方法可以告诉SQL Server不必在意行的顺序

五、except(差集)集合运算:先将其中完全重复的数据行删除,再返回只在第一个集合中出现,在第二个集合中不出现的所有行。

select tName,tSex from teacher 
except
select sName,sSex from student

ANSI SQL 支持带有all选项的except集合运算,但SQL Server 2008现在还不支持all选项。要想查询交集中的所有数据的办法:

with except_all as
(
    select row_number() over(partition by tName,tSex order by (select 0)) as rowNum,
        tName,tSex from teacher
    except
    select row_number() over(partition by sName,sSex order by (select 0)) as rowNum,
        sName,sSex from student
)
select tName,tSex from except_all

--备注:在排序函数的over子句中使用order by (select <常量>)用这种方法可以告诉SQL Server不必在意行的顺序

六、集合运算的优先级:intersect运算比union和except运算的优先级高,而union和except的优先级相等

原文地址:https://www.cnblogs.com/lusunqing/p/3273622.html