Allays return join 中左边 table 的值
Allays return value from left table in join
我有 2 table
A 和 B
A 有 cols(AKey, val1, val2)
B 有 Cols(BKey,Akey, ValX, valY)
我有以下查询
select a.Val1,a.Val2,b.ValX
from A
Left Join B on a.AKey = b.Akey
where a.Akey ={someValue}
and ((b.valY ={aDifferentVal}) or (b.valY is NULL))
情况是我总是想 return 来自 table A 的值。
这在连接中存在 {aDifferentVal} 时有效,当 table B 中没有值用于连接时它也有效,但是当 table 中有值用于连接但 [=其中 23=] 是 {aDifferentVal} 然后查询 return 什么都没有,我仍然想要来自 table A.
的值
我怎样才能做到这一点?
只需将 left join
ed table 上的条件从 where
子句移动到连接的 on
子句 - 否则它们将成为必需的,并且行它们未填满被归档(此处删除匹配但 valy
不匹配 {adifferentval}
的行):
select a.val1,a.val2,b.valx
from a
left join b
on b.akey = a.akey
and b.valy = {adifferentval}
where a.akey = {somevalue}
将 second table 上的条件移动到 on
子句:
select a.Val1,a.Val2,b.ValX
from A Left Join
B
on a.AKey = b.Akey and (b.valY ={aDifferentVal})
where a.Akey = {someValue}
where
子句中的过滤(某种程度上)将外连接转变为内连接。您的版本稍微好一些,因为它正在检查 NULL
。但是,匹配的行是:
- 与 B 完全不匹配的 A 值。
- 符合您指定条件的 A 值。
过滤掉的是与 B 中的行匹配的 A 值,但 none 匹配具有您指定的条件。
我有 2 table A 和 B
A 有 cols(AKey, val1, val2) B 有 Cols(BKey,Akey, ValX, valY)
我有以下查询
select a.Val1,a.Val2,b.ValX
from A
Left Join B on a.AKey = b.Akey
where a.Akey ={someValue}
and ((b.valY ={aDifferentVal}) or (b.valY is NULL))
情况是我总是想 return 来自 table A 的值。 这在连接中存在 {aDifferentVal} 时有效,当 table B 中没有值用于连接时它也有效,但是当 table 中有值用于连接但 [=其中 23=] 是 {aDifferentVal} 然后查询 return 什么都没有,我仍然想要来自 table A.
的值我怎样才能做到这一点?
只需将 left join
ed table 上的条件从 where
子句移动到连接的 on
子句 - 否则它们将成为必需的,并且行它们未填满被归档(此处删除匹配但 valy
不匹配 {adifferentval}
的行):
select a.val1,a.val2,b.valx
from a
left join b
on b.akey = a.akey
and b.valy = {adifferentval}
where a.akey = {somevalue}
将 second table 上的条件移动到 on
子句:
select a.Val1,a.Val2,b.ValX
from A Left Join
B
on a.AKey = b.Akey and (b.valY ={aDifferentVal})
where a.Akey = {someValue}
where
子句中的过滤(某种程度上)将外连接转变为内连接。您的版本稍微好一些,因为它正在检查 NULL
。但是,匹配的行是:
- 与 B 完全不匹配的 A 值。
- 符合您指定条件的 A 值。
过滤掉的是与 B 中的行匹配的 A 值,但 none 匹配具有您指定的条件。