1

在尝试outer join查询时,我注意到将一个条件从子句更改wherejoin子句会更改结果。这让我感到惊讶,但我将表格和查询简化如下,现在我想我明白了,但我想听听一个可靠的解释。

create table t0 (id int, b int);
create table t1 (id int, b int);
insert into t0 (id, b) values (1, 10), (2, 10);
insert into t1 (id, b) values (1, 2);

select t0.id, t0.b
from t0
left outer join t1 on 
    t0.id = t1.id
where
    t0.b = 10
    and
    t1.b = 2
;
 id | b  
----+----
  1 | 10
(1 row)

现在我将条件之一从子句where移到join子句:

select t0.id, t0.b
from t0
left outer join t1 on 
    t0.id = t1.id
    and
    t1.b = 2
where 
    t0.b = 10
;
 id | b  
----+----
  1 | 10
  2 | 10
(2 rows)

你知道如何写一个直截了当的推理吗?

4

1 回答 1

6

only的on条件决定了是否成功。如果连接失败,则连接的列将填充.outer joinjoinnull

另一方面,where子句从结果集中过滤出整行。

为了使这一点更清楚,t1.b添加到结果集中。作为t1.b = 2一个where条件,你得到:

t0.id   t0.b   t1.id   t1.b
1       10     1       2

t1.b = 2作为on条件::

t0.id   t0.b   t1.id   t1.b
1       10     1       2
2       10     NULL    NULL

您可以看到为什么该where子句将第二行过滤掉:null = 2不正确。

于 2012-06-09T17:12:28.950 回答