2009-06-10 60 views
2

我想左連接表A至表B其中tableA的某些條件爲真 所以我做這種類型的SQL查詢表A LEFT JOIN(的子集)表B

Select * from 
TableA Left Join TableB on TableA.fld1 = TableB.fld2 
where TableA.fld3 = True 

的這個工程確定。 但是現在我想只對表B中的某些記錄進行加入,即表B中某些條件得到滿足的那些記錄 ,具體爲fld4具有爲假爲其值。我想這樣做的原因是我想知道tableA中的哪些行在tableB中的行中沒有匹配,其中fld4false

如果我是刪除所有行TableB中,其中fld4並運行上述查詢 我會得到正確的結果。我所需要做的就是找到結果記錄集中的行在某個單元格中爲null。 但是,如果不是從表B中刪除行首先我改變查詢到一個低於我得到根本沒有行返回

Select * from 
TableA Left Join TableB on TableA.fld1 = TableB.fld2 
where TableA.fld3 = True 
and TableB.fld4 = false 

如果我的漫記意義可有人告訴我,我做錯了嗎? 謝謝

回答

5

把它聯接子句中:

select * from TableA 
left join TableB 
    on TableA.fld1 = TableB.fld2 
and TableB.fld4 = False 
where TableA.fld3 = True 

編輯:啊,我錯過了這一點:

我想知道哪些TableA中的行不具有TableB中fld4爲false的行之間的匹配。

喬爾的查詢會的工作,但因爲你不感興趣,從表B任何行,相關子查詢可能會更清潔:

select * from TableA 
where TableA.fld3 = True 
    and not exists (
    select * from TableB 
    where TableA.fld1 = TableB.fld2 
     and TableB.fld4 = False 
    ) 
+0

感謝您的超級快速響應! – jjb 2009-06-10 00:59:41

+0

感謝彼得,這對我來說並不容易,但我需要嘗試讓我的腦子圍繞子查詢的概念。 – jjb 2009-06-10 01:17:42

6

你應該把條件放在join子句中。當您有一個where子句過濾左連接查詢的「右側」行時,最終會排除行。試試這個:

Select * 
from TableA 
     Left Join TableB 
     on TableA.fld1 = TableB.fld2 
     and TableB.fld4 = false 
where TableA.fld3 = True 
+0

很大,非常感謝! – jjb 2009-06-10 01:00:17

3

我想知道哪些TableA中的行不在TableB中的fld4爲false的行之間有tableB中的匹配。

那麼你一定要做到這一點:

SELECT * 
FROM TableA 
LEFT JOIN TableB on TableA.fld1 = TableB.fld2 AND TableB.fld4 = False 
WHERE TableA.fld3 = True 
    AND TableB.fld4 IS NULL