SQL中intersect、union、minus和except 运算符

时间:2023-03-09 15:27:56
SQL中intersect、union、minus和except 运算符

1、intersect运算符
intersect运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (intersect  all),不消除重复行。
2、minus运算符
minus运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 all随 minus一起使用时 (minus all),不消除重复行。
3、union运算符

SQL中intersect、union、minus和except 运算符

.这三个关键字主要是对数据库的查询结果进行操作

union运算符是将两个或更多查询的结果组合为单个结果集

table1:
f_name  f_date
name1   2009-6-1
name2   2009-6-2

table2:
f_name  f_date
name3   2009-6-2
name4   2009-6-3

select f_date from table1 intersect select date from table2
结果:
name2   2009-6-2

select f_date from table1 union select f_date from table2
结果:

2009-6-1
2009-6-2
2009-6-3

注:except
只能用于SQLserver
在SQLserver中:
select f_date from table1 except select f_date from table2
结果:
2009-6-1
在oracle中用minus:
select f_date from table1 minus select f_date from table2
结果:
2009-6-1

并集 :union: select × from a union (all) select × from b aUb 
交集: intersect: select × from a intersect select × from b anb 
差集: minus: select × from a minus select × from b a-b

SQLServer中通过intersect,union,except和三个关键字对应交、并、差三种集合运算。

他们的对应关系可以参考下面图示

SQL中intersect、union、minus和except 运算符

测试示例:

构造A,B两个数据集

  1. A:1,2,3,4
  2. B:1,2,5
  3. WITH A AS
  4. (SELECT '1' tno
  5. UNION ALL SELECT  '2' UNION ALL SELECT  '3' UNION ALL SELECT  '4'
  6. ),
  7. B AS(SELECT '1' tno
  8. UNION ALL SELECT  '2' UNION ALL SELECT  '5')

查询示例:

1 Union 取合集并过滤重复数据

  1. --1 Union 取合集并过滤重复数据
  2. --结果显示: 1,2,3,4,5
  3. SELECT * FROM A
  4. UNION
  5. SELECT * FROM B;

2 Union all 取合集不过滤重复数据

  1. --2 Union all 取合集不过滤重复数据
  2. --结果显示:1,2,3,4,1,2,5
  3. SELECT * FROM A
  4. UNION  all
  5. SELECT * FROM B;

3 Intersect 取交集(两个表中都有数据)

  1. --3 Intersect 取交集
  2. --结果显示:1,2
  3. SELECT * FROM A
  4. Intersect
  5. SELECT * FROM B;

4 except 取差集(取A-B的记录)

    1. --4 except 取差集
    2. --结果显示:3,4
    3. SELECT * FROM A
    4. except
    5. SELECT * FROM B;