我有两张桌子,有很多-2-多的关系:
tableA (ida,valA)
tableB (美洲开发银行,valB)
tableAB (国际开发署、美洲开发银行)
我需要一个应该在每个tupple中返回的查询:
(国际开发协会、美洲开发银行、0/1 (如果相关或不相关)
下面是一些输入/输出示例:tableA
ida valA
1 b
2 s
3 ltableB
idb valB
11 aaa
22 bbb
33 ccctableAB
ida idb
1 11
2 33预期成果:
ida idb is_exists
1 11 1
2 11 0
1 33 0
2 33 1请注意,我不需要总是0的排列,例如ida=3或idb=22
这是因为这意味着在矩阵中整个行或列为0(这表明该行与另一个表没有任何关系)。
\ ida | | |
idb \ | 1 | 2 | 3
---------------------------
11 | 1 | 0 | 0
---------------------------
22 | 0 | 0 | 0
---------------------------
33 | 0 | 1 | 0发布于 2012-05-22 13:36:00
你需要的是一个有所有可能的配对的驾驶台。获得这一结果的一种方法是使用交叉连接从TableA和TableB获得:
select allAB.aid, allAB.bid, max(case when ab.aid is not null then 1 else 0 end) as HasPair
from (select distinct a.id as aid, b.id as bid
from TableA a cross join
TableB b
) as allAB left outer join
TableAB ab
on allAB.aid = ab.aid and
allAB.bid = ab.bid
group by allAB.aid, allAB.bid之后,查询只会总结并确定TableAB中是否有匹配的记录。
https://stackoverflow.com/questions/10703061
复制相似问题