sql交集:sql求交集与差集

日常工作中,针对两个表A,B,求A与B表中同一个字段的交集与差集是常见需求,下面我们来总结一下求交集与差集的方法。

假设现在有两张表A,B,A,B表中均有一个字段为id,现在我们想求
A与B中都存在的id有多少个(去重),在A中但不在B中的id有多少个。

1.求交集

1.1 通过join求交集

要求交集,我们最先想到的是可以通过join的方式来实现。

select count(distinct id) from A join Bon A.id = B.id;

常规的join操作,不解释。

1.2 通过in求交集

通过in操作实现求交集的功能。

select count(distinct id) from A where id in(select id from B);

1.3 通过exists求交集

select count(distinct id) from A where exists(select id from B where B.id = A.id);

exists可以用来判断是否存在。如果exists中的查询内容存在,结果则返回为真,否则为假。
如果exists在where条件中,会先对where条件前的主查询进行查询。待主查询完毕以后,会将结果代入exists中的子查询进行判断,最后根据判断结果,如果为true输出,false不输出。

2.求差集

如果是求差集,join的方式就不好用了,我们可以用not in或者not exists的方式来进行操作。

2.1 not in求差集

select count(distinct id) from A where id not in(select id from B where id is not null)

2.2 not exists求差集

select count(distinct id) from A where not exists(select id from B where B.id = A.id);

相关推荐

相关文章