我在三个字段上连接两个表。我遇到的问题是,如果 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
鲍勃纽约市
约翰·多伊纽约
jane doe 纽约市
b: foo bar baz fee fie
鲍勃·多伊纽约市 500 200
bob doe 默认值 100 100
约翰·多伊 CHI 300 200
约翰·多伊 默认 100 100
jane doe NYC 500 100
最佳答案
您必须添加一个 NOT EXISTS
以便在匹配 时排除具有
也存在:baz = 'DEFAULT'
的 b
记录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)
关于sql - 加入默认值但不想要叉积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310176/