SQL中这里的逻辑有点复杂。这是想法(比 SQL 更简单)。首先计算f1
每个表中每个元素的数量。您只需要在它们相等的地方保留对。
然后计算每对的共同点数f1
。当此计数与列的总计数匹配时,这些对匹配。
这是执行此操作的 SQL:
with t1 as (
select 1 as f1, 'A' as f2 union all
select 1, 'B' union all
select 2, 'C' union all
select 2, 'D' union all
select 2, 'E' union all
select 3, 'G' union all
select 3, 'H'
),
t2 as (
select 8 as f1, 'A' as f2 union all
select 8, 'B' union all
select 9, 'E' union all
select 9, 'D' union all
select 9, 'C' union all
select 10, 'F' union all
select 11, 'G' union all
select 11, 'H'
)
select driver.f11, driver.f12
from ((select t1.f1 as f11, f2cnt1, t2.f1 as f12, f2cnt2
from (select t1.f1, count(*) as f2cnt1
from t1
group by t1.f1
) t1 join
(select t2.f1, count(*) as f2cnt2
from t2
group by t2.f1
) t2
on t1.f2cnt1 = t2.f2cnt2
)
) driver join
(select t1.f1 as f11, t2.f1 as f12, count(*) as InCommon
from t1 join
t2
on t1.f2 = t2.f2
group by t1.f1, t2.f1
) common
on driver.f11 = common.f11 and
driver.f12 = common.f12
where driver.f2cnt1 = common.InCommon;
SQLFiddle 在这里。