oracle union與union all效率與區別分析

來源:互聯網
上載者:User

union 對兩個結果集進行並集操作,不包括重複行,同時進行預設規則排序;

union all 對兩個結果集進行並集操作,包括重複行,不進行排序


union all 要比union快很多,所以,如果可以確認合并的兩個結果集中不包含重複的資料的話,那麼就使用union all,如下:

盡量使用union all,因為union需要進行排序,去除重複記錄,效率低
union
如果表有多個索引列的時候,用union 替換 where 中的or 效率會提高不少。索引列使用or會造成全表掃描。如果有column 沒有使用索引,就得記得or了。

select date from store_information
union
select date from internet_sales

注意:union用法中,兩個select語句的欄位類型匹配,而且欄位個數要相同,如上面的例子,在實際的軟體開發過程,會遇到更複雜的情況,具體請看下面的例子

select '1' as type,fl_id,fl_code,fl_cname,flda.fl_parentid from flda
where zt_id=2006030002
union
select '2' as type,xm_id,xm_code ,xm_cname ,fl_id from xmda
where exists (select * from (select fl_id from flda where zt_id=2006030002 ) a where xmda.fl_id=a.fl_id)
order by type,fl_parentid ,fl_id

這個句子的意思是將兩個sql語句union查詢出來,查詢的條件就是看xmda表中的fl_id是否和主表flda裡的fl_id值相匹配,(也就是存在).

 

union all 詳細執行個體

union 指令的目的是將兩個 sql 語句的結果合并起來,可以查看你要的查詢結果.

例如:

 

sql>   select   *   from   a;

id                   name
----------   ----------
1                     aa
2                     bb
3                     cc
6                     dd
7                     ee

sql>   select   *   from   b;

id                   addr
----------   ----------
1                     aa
2                     bb
3                     cc
4                     dd
5                     ee

sql>   select   *   from   a
    2     union   all
    3     select   *   from   b;

id                   name
----------   ----------
1                     aa
2                     bb
3                     cc
6                     dd
7                     ee
1                     aa
2                     bb
3                     cc
4                     dd
5                     ee

已選擇10行。

sql>   select   *   from   a
    2     union  
    3     select   *   from   b;

id                   name
----------   ----------
1                     aa
2                     bb
3                     cc
4                     dd
5                     ee
6                     dd
7                     ee

已選擇7行。

sql>

注意:union用法中,兩個select語句的欄位類型匹配,而且欄位個數要相同,如上面的例子,在實際的軟體開發過程,會遇到更複雜的情況

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.