一、基本概念
差集:minus
交集:intersect
并集:union、union all。union将重複的元組去掉,union all則不會。
表store_information 店面營業表
store_name
sales
date
分店1
1500
2013-01-05
分店2
250
2013-01-07
300
2013-01-08
分店3
700
表internet sales 網絡營業表
850
2013-01-10
535
2013-01-11
320
2013-01-12
750
應用兩個集合的相減,相交和相加時,是有嚴格要求的:内部的select 語句必須擁有相同數量的列。列也必須擁有相似的資料類型。每條select
語句中的列的順序必須相同。
①兩個集合的字段必須明确,用*報錯
②字段類型和順序相同,名稱可以不同,如集合1的字段1是number,字段2是varchar,那集合2的字段1必須也是number,字段2必須是varchar
③不能排序,如果要對結果排序,可以在集合運算後,外面再套一個查詢,然後排序。
select * from (select order_id from made_order minus select order_id from charge_detail) order
by order_id
二、minus
select column_name(s) from table_name1
minus
select column_name(s) from table_name2
查找有店面營業額,但沒有網絡營業額的日期。
select date from store_information
select date from internet_sales
結果:
可以這樣了解,兩個表的date字段組成了一個[5,7,8,10,11,12]全集,減去網絡營業表的date[7,10,11,12]剩下[5,8]就是需要的結果。
三、union、union all
查找所有有營業額的日子
union
date
2013-01-05
2013-01-07
2013-01-10
union all 和 union 不同之處在于 union all 會将每一筆符合條件的資料都列出來,無論資料值有無重複。
union all
2013-01-08
四、intersect可以查相關資料
五、性能問題和注意點
雖然同樣的功能可以用簡單sql語句來實作,但性能差别非常大。made_order共23萬筆記錄,charge_detail共17萬筆記錄:
select order_id from made_order
select order_id from charge_detail
耗時:1.14 sec
select a.order_id from made_order a
where a.order_id not exists (
select order_id
from charge_detail
where order_id = a.order_id
)
耗時:18.19 sec
性能相差15.956倍。是以在遇到這種問題的時候,還是用minus,intersect和union all來解決問題。
原帖位址:
http://www.cnblogs.com/fxgachiever/archive/2010/09/10/1823057.html
http://blog.csdn.net/gan690416372/article/details/5012397