我要在三个场地合两张桌子。我遇到的问题是,如果a.baz不在b.baz中,我需要使用表b中的默认行。问题是有些在b中有一个匹配项,但也有一个默认值,这导致了一个我不想要的交叉积。

select a.foo, a.bar, a.baz, b.fee, b.fie
from a
join b
on a.foo = b.foo
and a.bar = b.bar
and ((a.baz = b.baz) or b.baz = 'DEFAULT')

电流输出:
foo  bar  baz   fee   fie
bob  doe  NYC   500   200
bob  doe  DEFUALT 100 100
john doe  DEFAULT 100 100
jane doe  NYC   500   500

期望输出:
foo  bar  baz   fee   fie
bob  doe  NYC   500   200
john doe  DEFAULT 100 100
jane doe  NYC   500   500

样本数据:
a: foo bar baz bob doe NYC john doe NYC jane doe NYC
b: foo bar baz fee fie bob doe NYC 500 200 bob doe DEFAULT 100 100 john doe CHI 300 200 john doe DEFAULT 100 100 jane doe NYC 500 100

最佳答案

当匹配NOT EXISTS也存在时,必须添加b以排除baz = 'DEFAULT'记录具有a.baz = b.baz

select a.foo, a.bar, a.baz, b.baz, b.fee, b.fie
from a
join b
on a.foo = b.foo and a.bar = b.bar and ((a.baz = b.baz) OR b.baz = 'DEFAULT')
where not exists (select 1
                  from b as b1
                  where a.foo = b1.foo and
                        a.bar = b1.bar and
                        b.baz = 'DEFAULT' and
                        b1.baz = a.baz)

Demo here

关于sql - 加入默认值但不想要叉积,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36310176/

10-12 00:23