SQL 查询在不等于的左连接中不包含有效结果

问题描述 投票:0回答:1

我的 SQL 查询未按预期执行并返回不完整的结果。在下面的查询中,如果 t2 中没有匹配的 id,则有效的 t1 行不会包含在查询结果中。

Select t1.id, t2.code
From table1 t1
left join t2 on t1.id = t2.id
where t2.code != 'value'

删除Where子句时,结果返回有效的t1.id数据,t2列中为空

Select t1.id, t2.code
From table1 t1
left join t2 on t1.id = t2.id

正确返回

t1.id | t2.code
1234  | null

我可以通过将 IIF 添加到Where 子句来解决这个问题,但是这种方法在我的报告工具中不是一个可行的解决方案:

Select t1.id, t2.code
From table1 t1
left join t2 on t1.id = t2.id
where iif(t2.code is null, '', t2.code) != 'value'

正确返回

t1.id | t2.code
1234  | null

为什么包含 t2.code != 'value' 会从结果中删除 t1.id = 1234 行?结果的 t2 侧为空,因此不等于“值”,因此该行不应该包含在结果中吗?

sql null where-clause left-join iif
1个回答
0
投票

您的 SQL 查询是通过将 WHERE 子句与 LEFT JOIN 结合使用而产生的。当您使用 LEFT JOIN 时,左表(在本例中为 table1、t1)中的所有行都将与右表 (t2) 中的匹配行基于它们之间的链接列进行组合。如果没有匹配,则右表一侧的结果为 NULL。 要包含 t2.id 不存在的 t1 行(即 t2.code 为 NULL),您应该在 WHERE 子句中显式检查 NULL 值

SELECT t1.id, t2.code
FROM table1 t1
LEFT JOIN t2 ON t1.id = t2.id
WHERE t2.code != 'value' OR t2.code IS NULL
© www.soinside.com 2019 - 2024. All rights reserved.