2009-12-02 152 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)