oracle union 性能,oracle中union和union all区别与性能分析

[ 概要 ]

经常写sql的同学可能会用到union和union all这两个关键词, 可能你知道使用它们可以将两个查询的结果集进行合并,

那么二者有什么区别呢? 下面我们就简单的分析下.

[ 比较 ]

union: 对两个结果集进行并集操作, 不包括重复行,相当于distinct, 同时进行默认规则的排序;

union all: 对两个结果集进行并集操作, 包括重复行, 即所有的结果全部显示, 不管是不是重复;

下面我们举一个简单的例子来证明上面的结论:

1. 准备数据:

drop table student;

create table student

(

id int primary key,

name nvarchar2(50) not null,

score number not null

);

insert into student values(1,‘Aaron‘,78);

insert into student values(2,‘Bill‘,76);

insert into student values(3,‘Cindy‘,89);

insert into student values(4,‘Damon‘,90);

insert into student values(5,‘Ella‘,73);

insert into student values(6,‘Frado‘,61);

insert into student values(7,‘Gill‘,99);

insert into student values(8,‘Hellen‘,56);

insert into student values(9,‘Ivan‘,93);

insert into student values(10,‘Jay‘,90);

commit;

2. 比较不同点

查询比较①

-- union all

select * from student where id < 4

union all

select * from student where id > 2 and id < 6

-- union

select * from student where id < 4

union

select * from student where id > 2 and id < 6union all 查询结果:

eaf1c121e71b8719a9742641e3f85644.png

union 查询结果:

3ce3428c84aaac62be8ad21feb172a14.png

通过比较不难看出, union all不会去掉重复记录, 而union去掉了重复的记录.

查询比较②

-- union all

select * from student where id > 2 and id < 6

union all

select * from student where id < 4

-- union

select * from student where id > 2 and id < 6

union

select * from student where id < 4union all 查询结果:

01e990ca2f7774ab790d5f4bef1197d3.png

union 查询结果:

48604bd7483282fe8c1f8435538b6515.png

通过比较不难看出, union all会按照关联的次序组织数据, 而union会依据一定的规则进行排序.

那么这个规则是什么呢? 我们通过下面的查询得出规律:

-- union

select score,id,name from student where id > 2 and id < 6

union

select score,id,name from student where id < 4

8ee3d0d66afafa20d3667e55f70dca3e.png

结论: 按照字段出现的顺序进行排序, 之前的查询相当于order by id, name, score, 刚刚的查询相当于order by score, id, name.

[ 总结 ]

1.  因为union all仅仅是简单的合并查询结果, 并不会做去重操作, 也不会排序, 所以union all效率要比union高.

所以在能够确定没有重复记录的情况下, 尽量使用union all.

2. 通常如果表有多个索引列时, 用union替换where子句中的or会起到较好的效果, 索引列使用or会造成全表扫描.

注意: 以上规则只针对多个索引列有效, 假如有column没有被索引, 那还是用or吧.

例如: 还是使用上面的例子, 假定name和score上建有索引.

-- 高效

select id, name, score from student where name like ‘%y%‘

union

select id, name, score from student where score between 80 and 90

-- 低效

select id, name, score from student where name like ‘%y%‘ or score between 80 and 90

原文:http://blog.csdn.net/zdp072/article/details/25744669

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值