gpt4 book ai didi

sql - LEFT JOIN 中的 On 或 Where 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 18:16:38 25 4
gpt4 key购买 nike

下面几段SQL代码有什么区别:

select count(*)
from A
left join B
on a.id = b.id
where a.status = 2 and
b.id is NULL


select count(*)
from A
left join B
on a.id = b.id
and a.status =2
where b.id is NULL

?我读到这个: Semantic difference between join queries但我还是不知道用哪个更好

I have spend the past hour reading this and grasping it all answers added value but I understood the code example together with "never encountered this" the best

最佳答案

如何使用 LEFT 连接是关键,一个将过滤结果,另一个只会使 LEFT 连接失败,保留 JOIN 左侧的数据。

(1) 在 a.id = b.id 上左连接 B
其中 a.status = 2

忽略其他过滤器,这表示对表 B 进行 LEFT JOIN,因此,“尝试使用条件 a.id=b.id 连接到表 B”。
如果您无法匹配,请保留左表中的记录(即 A)。之后,在剩余的记录上,过滤掉(即删除)不匹配的记录 a.status=2
(2)左连接B
a.id = b.id 和 a.status =2

忽略其他过滤器,这表示在 2 个条件下对表 B 进行 LEFT JOIN,因此,“尝试在两个条件下都加入表 B a.id = b.id and a.status =2”。如果在两种情况下都没有从 B 得到记录(即使一个与 B 无关),无论如何都要保留来自 A 的记录。

关于sql - LEFT JOIN 中的 On 或 Where 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458255/

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