[日期:2017-12-08] | [字体: 大 中 小 ] |
-- Oracle 中的复合查询
复合查询: 包含集合运算 (操作) 的查询
常见的集合操作有:
union: 两个查询的并集 (无重复行、按第一个查询的第一列升序排序)
union all:两个查询的并集 (有重复行)
intersect:两个查询的交集 (无重复行、按第一个查询的第一列升序排序)
minus: 两个查询的差集 (无重复行、按第一个查询的第一列升序排序), 取第一张表有而第二张表没有的所有记录
由于 union、intersect、minus 存在排序,故而对 sql 性能的影响很大,建议少用。
-- 测试
create table t1 (id number,name varchar2(20));
create table t2 (id number,name varchar2(20));
insert into t1 values(1,'表 1');
insert into t1 values(2,'表 1');
insert into t1 values(3,'表 1');
insert into t1 values(4,'表 1');
insert into t1 values(5,'表 1');
insert into t2 values(3,'表 2');
insert into t2 values(4,'表 2');
insert into t2 values(5,'表 2');
insert into t2 values(6,'表 2');
insert into t2 values(7,'表 2');
-- 查询 t1 和 t2
SQL> select * from t1;
ID NAME
---------- --------------------
表 1
表 1
表 1
表 1
表 1
SQL> select * from t2;
ID NAME
---------- --------------------
表 2
表 2
表 2
表 2
表 2
-- 并集
--1.union
select id from t1
union
select id from t2 ;
SQL> select id from t1
union
select id from t2 ;
ID
----------
2
4
6
rows selected
--2.union all
select id from t1
union all
select id from t2;
SQL> select id from t1
union all
select id from t2;
ID
----------
2
4
3
5
7
rows selected
-- 交集
select id from t1
intersect
select id from t2;
SQL> select id from t1
intersect
select id from t2;
ID
----------
4
-- 差集
select id from t1
minus
select id from t2;
SQL> select id from t1
minus
select id from t2;
ID
----------
2
来源: http://www.linuxidc.com/Linux/2017-12/149247.htm