一個直接的解決方案:
select count(*)
from (select 1
from (
select 'a' as tab,ip from a
union all select 'b' as tab,ip from b
union all select 'c' as tab,ip from c
) t
group by ip
having count(case when tab = 'a' then 1 end) > 0
and count(case when tab = 'b' then 1 end) > 0
and count(case when tab = 'c' then 1 end) > 0
) t
這會給你信息不僅關於3個表交點(IN_A = 1,IN_B = 1,in_c = 1),而且信息在所有其它組合:
select in_a
,in_b
,in_c
,count(*) as ips
from (select max(case when tab = 'a' then 1 end) as in_a
,max(case when tab = 'b' then 1 end) as in_b
,max(case when tab = 'c' then 1 end) as in_c
from (
select 'a' as tab,ip from a
union all select 'b' as tab,ip from b
union all select 'c' as tab,ip from c
) t
group by ip
) t
group by in_a
,in_b
,in_c
...甚至一些更多的信息:
select sign(cnt_a) as in_a
,sign(cnt_b) as in_b
,sign(cnt_c) as in_c
,count(*) as unique_ips
,sum(cnt_total) as total_ips
,sum(cnt_a) as total_ips_in_a
,sum(cnt_b) as total_ips_in_b
,sum(cnt_c) as total_ips_in_c
from (select count(*) as cnt_total
,count(case when tab = 'a' then 1 end) as cnt_a
,count(case when tab = 'b' then 1 end) as cnt_b
,count(case when tab = 'c' then 1 end) as cnt_c
from (
select 'a' as tab,ip from a
union all select 'b' as tab,ip from b
union all select 'c' as tab,ip from c
) t
group by ip
) t
group by sign(cnt_a)
,sign(cnt_b)
,sign(cnt_c)
給予好評,因爲一)語法的工作和b)報復downvotes是瘸腿的。 – TheProletariat
@DuduMarkovitz我沒有親自採取 - 我刪除了我的答案,因爲有兩個更好的答案,我的並沒有增加太多。我沒有反擊你投票。 – Siyual
@DuduMarkovitz非常好用,但是我如何得到所有3個表中存在的所有數據?我可以從中選擇一個計數(*),其中in_a = 1,in_b = 1和in_c = 1,還是有更好的方法? –
TheProletariat