2009-12-02 121 views
0

我有這個簡單的查詢:快速左連接問題

SELECT f.id, f.format_type, h.newspaper_id 
FROM newspapers_formats f 
LEFT JOIN newspapers_formats_held h 
ON (f.id = h.format_id) 

這將返回我們有這種格式的所有format_types,格式ID和報紙ID。我需要的是那麼它僅限制於newspaper_id = X,但是,如果我這樣做了WHERE,像這樣:

SELECT f.id, f.format_type, h.newspaper_id 
FROM newspapers_formats f 
LEFT JOIN newspapers_formats_held h 
ON (f.id = h.format_id) 
WHERE h.newspaper_id=3 

然後我只得到,我們有在報紙的格式。不管報紙是否擁有,我仍然需要所有格式。

希望這是有道理的。如有需要,請求澄清。

回答

4

您可以查詢更改爲

SELECT f.id, f.format_type, h.newspaper_id 
    FROM newspapers_formats f 
    LEFT JOIN newspapers_formats_held h 
    ON (f.id = h.format_id) 
    AND h.newspaper_id=3 
2
 
SELECT f.id, f.format_type, h.newspaper_id 
    FROM newspapers_formats f 
     LEFT JOIN newspapers_formats_held h ON (f.id = h.format_id) 
    WHERE h.newspaper_id = 3 
     OR h.format_id IS NULL 
1

你需要把你的過濾條件的ON子句。像這樣:

SELECT f.id,f.format_type,h.newspaper_id FROM newspapers_formats˚F LEFT JOIN newspapers_formats_heldħ ON(f.id = h.format_id) AND h.newspaper_id = 3

0

Dewayne的回答非常好。

也許使用不同將會更好。

4

這是ON子句中的條件與where子句中查詢行爲不同的一個很好的例子。對於WHERE子句,返回的記錄必須匹配。這不包括行不匹配newspaper_formats因爲這些行報id爲NULL,NULL和!= 3

Format_type newspaper_id 
1   NULL   Exclude because null != 3 
1   3    Include because 3=3 
1   2    Exclude because 2 !=3 

要包括所有的格式類型,你希望把這個標準的連接條件。左外連接的標準定義:「從連接左側的表中檢索所有記錄,並僅從與連接右側表中的連接標準匹配的記錄中檢索。」連接標準必須在ON中,而不是在WHERE中。

SELECT f.id, f.format_type, h.newspaper_id 
FROM newspapers_formats f 
LEFT JOIN newspapers_formats_held h 
ON (f.id = h.format_id AND h.newspaper_id=3)