Heim  >  Artikel  >  Datenbank  >  union与union all 的区别

union与union all 的区别

WBOY
WBOYOriginal
2016-06-07 17:37:3910927Durchsuche

union与union all 的区别 Union与Union All的区别 如果我们需要将两个select语句的结果作为一个整体显示出来,我们就需要用到union或者union all关键字。union(或称为联合)的作用是将多个结果合并在一起显示出来。 union和union all的区别是,union会自动压缩

union与union all 的区别

Union与Union All的区别

如果我们需要将两个select语句的结果作为一个整体显示出来,我们就需要用到union或者union all关键字。union(或称为联合)的作用是将多个结果合并在一起显示出来。

union和union all的区别是,union会自动压缩多个结果集合中的重复结果,而union all则将所有的结果全部显示出来,不管是不是重复。


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

Union All:对两个结果集进行并集操作,包括重复行,不进行排序;

Intersect:对两个结果集进行交集操作,,不包括重复行,同时进行默认规则的排序;

Minus:对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序。

可以在最后一个结果集中指定Order by子句改变排序方式。

例如:

select employee_id,job_id from employees
union
select employee_id,job_id from job_history

以上将两个表的结果联合在一起。这两个例子会将两个select语句的结果中的重复值进行压缩,也就是结果的数据并不是两条结果的条数的和。如果希望即使重复的结果显示出来可以使用union all,例如:

2.在oracle的scott用户中有表emp
select * from emp where deptno >= 20
union all
select * from emp where deptno 这里的结果就有很多重复值了。

有关union和union all关键字需要注意的问题是:

union 和 union all都可以将多个结果集合并,而不仅仅是两个,你可以将多个结果集串起来。
使用union和union all必须保证各个select 集合的结果有相同个数的列,并且每个列的类型是一样的。但列名则不一定需要相同,oracle会将第一个结果的列名作为结果集的列名。例如下面是一个例子:
select empno,ename from emp
union
select deptno,dname from dept
我们没有必要在每一个select结果集中使用order by子句来进行排序,我们可以在最后使用一条order by来对整个结果进行排序。例如:
select empno,ename from emp
union
select deptno,dname from dept
order by ename;

 

--实例

SQL> select * from stud;

SID        KCBM               CJ RQ            
---------- ---------- ---------- ---------- -
1          语文               60 10-1月 -05
2          数学               60 02-10月-05
3          英语               90 25-1月 -05
1          数学               99 10-1月 -05
3          数学               60 25-1月 -05
2          语文               20 02-10月-05
4          语文               35 25-1月 -05
4          数学               55 25-1月 -05
4          英语               50 25-1月 -05

已选择9行。

SQL> select cj from stud
  2  union
  3  select avg(cj) from stud;

        CJ
----------
        20
        35
        50
        55
58.7777778
        60
        90
        99

已选择8行。

SQL> select cj from stud
  2  union all
  3  select avg(cj) from stud;

 

 

     

   CJ
----------
        60
        60
        90
        99
        60
        20
        35
        55
        50
58.7777778

已选择10行。
union 排序,union all 不排序

posted on

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn