Oracle中minus取差集与intersect取交集

Oracle中minus取差集与intersect取交集

最近在业务中遇到需要取两个结果集中的差集。

    首先想到的是加条件where id not in(select id from table)这种类似的SQL语句,但是这种sql随着表数据的增加,后面的数据肯定会越来越多,所消耗的时间也会越来越久,所以觉得不可行。
    其次,我想到java中有存在对于两个集合方法:list1.removeAll(list2)来取差集,如果SQL返回两个结果集这种方法也可以实现,但再看list1.removeAll(list2)底层的实现是通过迭代,再每个元素调用contains()方法来实现的,故再数据量大的时候,这种方法的时间复杂度还是很高的,故也觉得不可行。
Oracle中minus取差集与intersect取交集
    后来百度Oracle中有现成的函数minus来获取两个结果集的差集,来记录一下。

minus:返回左边表减去右边表的数据,也就是差集。并且minus有剃重的作用。
语法:
select column1,column2 from table1 minus select column1,column2 from table2 ;

select column1,column2 from table1 minus select column1,column2 from table2 where id='xxx';
注:table1,tanle2可以是相同的表,也可以是不同的表,只要查询出来的列column1,column2相同就行。

intersect:返回左右两边表都有的数据(和上面用法一样)
语法:
select column1,column2 from table1 intersect select column1,column2 from table2 ;

select column1,column2 from table1 intersect select column1,column2 from table2 where id='xxx';

总结:
使用minus取差集,使用intersect取交集,当然还有最常用的union all取并集。
同时使用minus的效率也大于使用 not in 和 not exists这种查询方式的。