I have 2 tables A and B
A has cols(AKey, val1, val2) B has Cols(BKey,Akey, ValX, valY)
i have the following query
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))
The situation is that i always want to return the values from table A. and this works when {aDifferentVal} exists in the the join, it also works when there are no values in table B for the Join, However when there are values in table be for the Join but none of these are {aDifferentVal} then the query return nothing, and i still want the values from table A.
How can i achieve this?
Advertisement
Answer
Just move the condition on the left join
ed table from the where
clause to the on
clause of the join – otherwise they become mandatory, and rows where they are not fullfilled are filered out (here this removes rows that match but whose valy
does not match {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}