sql - OUTER JOIN 中的条件给出与 WHERE 条件中不同的结果

标签 sql postgresql

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

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)

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

最佳答案

外连接on 条件仅确定连接 是否成功。如果连接失败,连接的列将填充为 null

另一方面,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 不正确。

关于sql - OUTER JOIN 中的条件给出与 WHERE 条件中不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10962892/

相关文章:

SQL 数据库 - 何时使用单独的表与现有表的列?

sql - 棘手的选择语句

sql - 检查字符串是否为日期 Postgresql

ruby-on-rails - rails : Error installing pg gem

postgresql - Postgres : ERROR: operator does not exist: character varying = bigint

postgresql - 如何检查多线串是否真的是多线串?

mysql - 如何制作一个简单的公交路线搜索引擎?

php - MySQL 过期

php - PostgreSQL 原始 SQL 插入 (Laravel 5.5)

sql - 初学者SQL问题: arithmetic with multiple COUNT(*) results