Sql中的union和union all的講解

來源:互聯網
上載者:User

標籤:

SQL UNION 和 UNION ALL操作符

UNION 操作符用於合并兩個或多個 SELECT 語句的結果集。

請注意,UNION 內部的 SELECT 語句必須擁有相同數量的列。列也必須擁有相似的資料類型。同時,每條 SELECT 語句中的列的順序必須相同。

假設我們有一個表Student,包括以下欄位與資料:

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;

Union和Union All的區別。

select *
from student
where id < 4

union

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

結果將是

1    Aaron    78
2    Bill    76
3    Cindy    89
4    Damon    90
5    Ella    73

如果換成Union All串連兩個結果集,則返回結果是:

1    Aaron    78
2    Bill    76
3    Cindy    89
3    Cindy    89
4    Damon    90
5    Ella    73

可以看到,Union和Union All的區別之一在於對重複結果的處理。

 

  UNION在進行錶鏈接後會篩選掉重複的記錄,所以在錶鏈接後會對所產生的結果集進行排序運算,重複資料刪除的記錄再返回結果。實際大部分應用中是不會產生重複的記錄,最常見的是過程表與曆史表UNION。如:
select * from gc_dfys
union
select * from ls_jg_dfys
  這個SQL在運行時先取出兩個表的結果,再用排序空間進行排序重複資料刪除的記錄,最後返回結果集,如果表資料量大的話可能會導致用磁碟進行排序。
 而UNION ALL只是簡單的將兩個結果合并後就返回。這樣,如果返回的兩個結果集中有重複的資料,那麼返回的結果集就會包含重複的資料了。
 從效率上說,UNION ALL 要比UNION快很多,所以,如果可以確認合并的兩個結果集中不包含重複的資料的話,那麼就使用UNION ALL,                        

Sql中的union和union all的講解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.