一、基本概念
差集: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