阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

深入理解Oracle中的集合操作与复合查询

148次阅读
没有评论

共计 1371 个字符,预计需要花费 4 分钟才能阅读完成。

–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

更多 Oracle 相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-12/149247.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-22发表,共计1371字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中