create table #t1 (id int)
create table #t2 (id int)
insert into #t1 values (1)
insert into #t1 values (2)
insert into #t1 values (3)
insert into #t2 values (1)
insert into #t2 values (2)
我运行了以下查询,得到了 2 个不同的输出。
其次是所需的输出。
我无法理解 query1 给出的输出原因。
请协助我了解结果。
-- Query1
select * from #t1 a left join #t2 b on a.id = b.id and b.id is null
-- Query2
select * from #t1 a left join #t2 b on a.id = b.id where b.id is null
最佳答案
在查询 1 中,我们在连接条件中有 b.id is null
,因为在 A 上进行 LEFT JOIN
会返回 A 的所有行,而不管 JOIN 条件如何,因此 < strong>返回表 A 的 3 行。
在查询 2 中,A 上的第一个 LEFT JOIN
返回 3 行,然后 where b.id is null
应用于这 3 行,留下第三行并产生对于 id=3 的第三行,只有 1 行。
进一步说明:
你的评论
Though in Query1 how come b.id is null ??
需要详细解释
正如我在查询 1 中所说,对于 A 的每一行,Left join 不管 JOIN 的条件如何都会返回一行
所以你的加入条件实际上是
a.id = b.id且b.id为空
两个条件之间的逻辑 And 不能同时为真,就好像 b.id 为 null 为真那么 a.id=null 被匹配,这基本上是 null
输出在此 fiddle 中给出:http://sqlfiddle.com/#!3/c20ba/1
就像
id | id
________
1 | null
2 | null
3 | null
另一点要注意: 请注意,在 SQL 中 id=NULL
被评估为 NULL
。另请注意,在 sql 查询中执行逻辑运算(如 AND OR)时,NULL 的行为非常特殊。查看msdn documentation关于这种行为
null and true = null
null and false=false
null and null =null
null or null =null
null or true= true
null or false=null
关于sql-server - JOIN 中的 IS NULL 条件与查询中的 WHERE 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32714329/