Oracle中複合查詢(compound query)包括union,union all , minus,intersect,
union進行排序,默認以第一列升序排序,並且不包括重複記錄。
union all則不會排序,並且不會進行distinct操作,所以速度較快。
以下兩個查詢的結果是相同的
select distinct * from (select id from a union all select id from b) order by 1;
select id from a union select id from b;
intersect選擇兩個查詢的交集,調換兩個查詢順序不影響查詢結果;
minus選擇第一個查詢的結果,但不能包含第二個查詢中的記錄。
除了union all不會對結果進行排序和distinct,其他三個compound query都會對結果進行distinct和sort操作。
compound query中的子查詢的列數和類型必須相同;
select 1,2 from dual union select 1, null from dual; --correct
select 1 first,2 second from dual union select 1 one, '' two from dual; --not correct
select 1 first,'2' second from dual union select 1 one, '' two from dual; --correct
order by clause can only appear at the very end of the statement.