gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:31:41 25 4
gpt4 key购买 nike

在尝试 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com