日常工作中,針對兩個表A,B,求A與B表中同一個字段的交集與差集是常見需求,下面我們來總結(jié)一下求交集與差集的方法。
假設(shè)現(xiàn)在有兩張表A,B,A,B表中均有一個字段為id,現(xiàn)在我們想求
A與B中都存在的id有多少個(去重),在A中但不在B中的id有多少個。
1.求交集
1.1 通過join求交集
要求交集,我們最先想到的是可以通過join的方式來實現(xiàn)。
select count(distinct id) from A
join B
on A.id = B.id;
常規(guī)的join操作,不解釋。
1.2 通過in求交集
通過in操作實現(xiàn)求交集的功能。
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中的查詢內(nèi)容存在,結(jié)果則返回為真,否則為假。
如果exists在where條件中,會先對where條件前的主查詢進行查詢。待主查詢完畢以后,會將結(jié)果代入exists中的子查詢進行判斷,最后根據(jù)判斷結(jié)果,如果為true輸出,false不輸出。文章來源:http://www.zghlxwxcb.cn/news/detail-415864.html
2.求差集
如果是求差集,join的方式就不好用了,我們可以用not in或者not exists的方式來進行操作。文章來源地址http://www.zghlxwxcb.cn/news/detail-415864.html
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);
到了這里,關(guān)于sql求交集與差集的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!