您的位置:首页 > 数据库

SQL中Union与Union All的区别

2014-07-31 20:15 288 查看
在写SQL查询语句时,经常会碰到类似于这种的需求:查询年龄大于60岁的男职工以及所有出生于1950年的职工。在处理这种需求时,无法使用一条简单的SQL语句查询出所有满足条件的结果,此时就需要将这种需求划分为几个小的子需求,然后将子查询得到的结果集合合并即得到了满足查询条件的结果。为了处理类似于这种的需求,SQL提供了Union和Union All操作,如下所示:

[sql]
view plaincopyprint?

select * from employee 

where gender='M'
and year('2013-09-21')-year(birthday) > 60   

union (all)   

select *  from employee  

where year(birthday)=1950  

with ur;   --片段一 

select * from employee
where gender='M' and year('2013-09-21')-year(birthday) > 60
union (all)
select *  from employee
where year(birthday)=1950
with ur;   --片段一


那么这两个操作有什么区别呢,请参看以下例子,为了验证该例子我们创建一个employee表并向其中添加一些数据,具体示例代码如下所示:

[sql]
view plaincopyprint?

create table employee(eid
integer not
null, birthday date
not null, 

gender char(1), name
varchar(100), mbltel char(13), mail
varchar(20); --片段2 

create table employee(eid integer not null, birthday date not null,
gender char(1), name varchar(100), mbltel char(13), mail varchar(20); --片段2


[sql]
view plaincopyprint?

insert into employee
values 
(1, '1989-01-01','M','李一','1345663221','1345663221@139.com'), 

(2, '1952-01-01','M','李二','1345663331','1345663331@139.com'), 

(3, '1951-01-01','F','李三','1345664311','1345664311@139.com'), 

(4, '1950-01-01','M','李四','1345662111','1345662111@139.com'), 

(5, '1950-07-01','F','李五','1345343221','1345343221@139.com'); 
--片段三 

insert into employee values
(1, '1989-01-01','M','李一','1345663221','1345663221@139.com'),
(2, '1952-01-01','M','李二','1345663331','1345663331@139.com'),
(3, '1951-01-01','F','李三','1345664311','1345664311@139.com'),
(4, '1950-01-01','M','李四','1345662111','1345662111@139.com'),
(5, '1950-07-01','F','李五','1345343221','1345343221@139.com');  --片段三


分别执行样例代码片段一中的Union和Union All操作,会出现以下结果:

从上面查询得到的结果我们可以看出,Union All操作仅仅是简单的将两个子查询结果集直接求并操作,并不会剔除掉两者结果集中重复的部分,而Union操作除了会剔除掉结果集中重复的部分以外,还会对结果集进行排序(其实执行的实质逻辑应该是先将某一子结果集进行排序,然后再判断是否有重复的数据,若有则删除掉重复的数据)。

小tips:由于Union需要对查询结果集进行排序操作,当数据量较大时,若非特殊需要,尽量不要使用Union操作,而改用Union All操作,然后对Union All出来的结果执行去重操作即可,这样会使得查询的效率大大的增强。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐