Sql 使用左外部联接时,即使记录不存在,也返回行
当Sql 使用左外部联接时,即使记录不存在,也返回行,sql,Sql,当RepDailyCollection.IsReceived=0并且RepDailyCollection确实有该特定RepDailyInfoID的记录时,我试图从RepDailyInfo表中获取日期。这在SQLServer2005中可能吗 Select distinct RepDailyInfo.Date from RepDailyInfo left outer join RepDailyCollection c on c.RepDailyInfoID = RepDailyInfo
RepDailyCollection.IsReceived=0
并且RepDailyCollection
确实有该特定RepDailyInfoID
的记录时,我试图从RepDailyInfo
表中获取日期。这在SQLServer2005中可能吗
Select distinct RepDailyInfo.Date
from RepDailyInfo
left outer join RepDailyCollection c
on c.RepDailyInfoID = RepDailyInfo.RepDailyInfoID
where c.IsReceived = 0
or c.IsReceived = null
你可能想做什么
where IsNull(c.IsReceived,0) = 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)
WHERE
子句在外部联接之后进行过滤。如果不希望出现这种行为,请将WHERE
子句移动到JOIN
的ON
子句中,如下所示:
select distinct r.date
from RepDailyInfo r
left outer join RepDailyCollection c on c.RepDailyInfoID = r.RepDailyInfoID
and isnull(c.IsReceived, 0) = 0
将条件移动到联接的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)
还要注意在或
周围使用括号,这在SQL中是必需的,因为“或”优先于“和”,没有括号,最后会出现“(A和B)或“C”谢谢!我不知道我能在外接中写“and”条件。很想知道。再次感谢!!:-)没问题。事实上,这种技术非常方便,这是hibernate无法做到的,如果您试图编写这种性质的HQL查询,应该记住这一点-您必须使用本机SQL查询而不是HWL查询。@ram我认为c.IsReceived=null
应该c.IsReceived为null
@ram Yep-错误已更正。我真不敢相信我错过了。谢谢