使用左外连接时,即使记录不存在,也返回行

时间:2012-04-11 19:58:28

标签: sql

我想在RepDailyInfoRepDailyCollection.IsReceived = 0以及RepDailyCollection确实拥有特定RepDailyInfoID的记录时从Select distinct RepDailyInfo.Date from RepDailyInfo left outer join RepDailyCollection c on c.RepDailyInfoID = RepDailyInfo.RepDailyInfoID where c.IsReceived = 0 or c.IsReceived = null 表中获取日期。这可能在sql server 2005中吗?

{{1}}

4 个答案:

答案 0 :(得分:1)

将条件移动到连接的ON子句中,因为否则您需要连接来查找WHERE子句中要引用的行的行:

Select distinct RepDailyInfo.Date 
from RepDailyInfo 
left outer join RepDailyCollection c 
    on c.RepDailyInfoID = RepDailyInfo.RepDailyInfoID
    and (c.IsReceived = 0 or c.IsReceived is null)

另请注意在or周围使用括号,因为“或”优先于“和”而没有括号,最终会得到“(A和B)或C”

答案 1 :(得分:0)

您可能想要

where IsNull(c.IsReceived,0) = 0

答案 2 :(得分:0)

是的,但您必须在连接中过滤右侧的连接:

Select distinct RepDailyInfo.Date 
from RepDailyInfo 
left outer join RepDailyCollection c 
    on c.RepDailyInfoID = RepDailyInfo.RepDailyInfoID
   and (c.IsReceived = 0 
    or c.IsReceived is null)

答案 3 :(得分:0)

WHERE子句在OUTER JOIN之后进行过滤。如果您不想要这种行为,请将WHERE子句移到ON的{​​{1}}子句中,如下所示:

JOIN