oracle 交集和并集

今天研究了一下oracle 交集和并集,下面把我经过查找资料,测试后,整理如下:

1.并集

表1:

insert into student1 values(1,'学生1');
insert into student1 values(1,'学生2');
insert into student1 values(1,'学生3');

表2:

insert into student2 values(1,'学生1');
insert into student2 values(1,'学生4');
insert into student2 values(1,'学生5');

并集语句:

  1. select *from student1  
  2. union all  
  3. select *from student2  
select *from student1
union all
select *from student2


查后后结果

看到测试结果就明白了,union all对两个结果集进行并集操作,包括重复行,不进行排序。

如果去掉all 关键字,

  1. select *from student1  
  2. union  
  3. select *from student2  
select *from student1
union
select *from student2


看到结果,得出的结论是:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序

2.交集

  1. select *from student1  
  2. intersect  
  3. select *from student2  
select *from student1
intersect
select *from student2

结果为:

是的,返回查询结果中相同的部分即是他们的交集

补充一下:minus 关键字

查询时候把表1放在前面,

  1. select *from student1  
  2. minus  
  3. select *from student2  
select *from student1
minus
select *from student2

结果为:

查询时候把表2放在前面,

  1. select *from student2  
  2. minus  
  3. select *from student1  
select *from student2
minus
select *from student1


结果为:

使用 minus  返回在第一个查询结果中与第二个查询结果不相同的那部分行记录,即两个结果的差集

使用以上查询的结果集有两个最基本的规则:
(1)所有查询中的列数和列的顺序必须相同。
(2)数据类型必须兼容

 
原文地址:https://www.cnblogs.com/jiazuzhuzhu/p/6719339.html