2012-04-11 74 views
2

我試圖從RepDailyInfo表中獲得日期,當RepDailyCollection.IsReceived = 0RepDailyCollection確實有特定RepDailyInfoID的記錄時。這可能在SQL Server 2005中?即使使用左外部連接時不存在記錄,也要返回行

Select distinct RepDailyInfo.Date 
from RepDailyInfo 
left outer join RepDailyCollection c 
    on c.RepDailyInfoID = RepDailyInfo.RepDailyInfoID 
where c.IsReceived = 0 
    or c.IsReceived = null 

回答

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左右括號,這是需要在SQL的,因爲「或」優先「和」和不帶括號的你結束於「(A和B)或C」

+0

謝謝!我不知道我可以在外部連接寫'和'條件。有趣的知道。再次感謝!! :-) – Ram 2012-04-11 20:05:42

+1

沒問題。實際上,這種技術非常方便,它可以讓**不做**,如果您嘗試編寫這種性質的HQL查詢,應該記住這一點 - 您必須使用原生SQL查詢而不是HWL查詢。 – Bohemian 2012-04-11 20:08:37

+1

@ram我相信'c.IsReceived = null'應該是'c.IsReceived爲null'。 – 2012-04-11 20:40:34

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) 
0

WHERE子句的OUTER JOIN後過濾。如果你不希望這樣的行爲,將WHERE條款列入JOINON條款,像這樣:

select distinct r.date 
from RepDailyInfo r 
left outer join RepDailyCollection c on c.RepDailyInfoID = r.RepDailyInfoID 
    and isnull(c.IsReceived, 0) = 0 
相關問題