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語句的欄位類型匹配,而且欄位個數要相同,如上面的例子,在實際的軟體開發過程,會遇到更複雜的情況