2014-09-03 185 views
0

我試圖連接兩個表ORDER和ORDER_FLG。我想從ORDER中取出ORDER_FLG表中沒有Flg爲'Y'的所有列。左連接 - 連接兩個表並從左表中拉出所有數據

ORDER

Branch_nbr |Order_Id | Order_start_dt |Order_end_dt 
0001 | 110000 | 01/01/2014 | 02/02/2014 
0002 | 110001 | 03/03/2014 | 04/04/2014 
0003 | 110002 | 05/05/2014 | 06/06/2014 

ORDER_FLG

Branch_Nbr |Order_Id |Flg 
0001 | 110000| Y 
0003 | 110002| N 

SQL:

SELECT A.* 
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B 
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id 
WHERE A.Order_start_dt >= 'SOME_DATE' 
AND A.Order_end_dt <= 'SOME_DATE' 
AND B.Flg <> 'Y' 

我應該得到兩行(110002,110001)的輸出,但我得到的只有一個。如果第二個表中不存在條目,則數據不會從第一個表中提取。不應該從第一個表中拉出所有數據?

我嘗試這樣做,它的工作原理,但需要時間 -

SELECT A.* 
FROM ORDER AS A 
WHERE A.Order_start_dt >= 'SOME_DATE' 
AND A.Order_end_dt <= 'SOME_DATE' 
AND A.Order_Id NOT IN (SELECT Order_Id FROM ORDER_FLG 
WHERE Order_Id=A.Order_Id AND Branch_nbr=A.Branch_nbr 
AND Flg='Y') 
+0

嗨。任何答案都有幫助嗎?如果是的話,你應該接受它:) – PawelP 2014-09-13 11:34:05

回答

1

你的where子句中包括你的外部表的引用: AND B.Flg <> 'Y'

這where子句外後應用加入。來自外連接表的沒有匹配的行將在結果集中有空值。 Null與您的約束不匹配,因此行將從結果集中刪除。

Try this instead: 
SELECT A.* 
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B 
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id 
AND B.Flg <> 'Y' 
WHERE A.Order_start_dt >= 'SOME_DATE' 
AND A.Order_end_dt <= 'SOME_DATE' 
1

試試這個:

SELECT A.* 
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B 
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id 
WHERE A.Order_start_dt >= 'SOME_DATE' 
AND A.Order_end_dt <= 'SOME_DATE' 
AND (B.Flg IS NULL OR B.Flg <> 'Y') 

的B.Flg <> 'Y' 的條件是那些在ORDER_FLG沒有匹配的行所有的訂單顯然是錯誤的。你在這些字段中得到一個NULL,所以你必須在WHERE子句中允許這種可能性。

+0

這是一個很好的解決方案。另一種方法是,如果您不關心如何在ORDER_FLG表中添加數據,則將'B.Flg ='Y'添加到此連接條件中,並僅用'B.Flg IS NULL'完成WHERE子句 – ludwigmace 2014-09-03 17:02:25