【问题标题】:Result of various Joins on a scenario场景中各种连接的结果
【发布时间】:2019-03-28 20:29:05
【问题描述】:

我有两个表 test1 和 test2 都有包含一些值的单列。

我已经应用了内连接和外连接,但对输出感到困惑。

Create table test1
( id int)
insert into test1 values (1)
insert into test1 values (1)
insert into test1 values (1)


Create table test2
( id int)
insert into test2 values (1)
insert into test2 values (1)
insert into test2 values (NULL)

select a.id from test1 a inner join test2 b on a.id = b.id

我期待,

1
1
Null

作为内连接、左连接和右连接的输出。

但原来的输出是,

1
1
1
1
1
1

能否请您帮助我理解所有连接的这一点。

【问题讨论】:

标签: sql-server


【解决方案1】:

test1 中的三个 1 中的每一个都与test2 中的两个 1 中的每一个相连接,这产生了您在结果集中获得的 3x2=6 行。 test1 中的第一个、第二个和第三个 1 没有什么不同,test2 中的第一个和第二个 1 没有什么不同。

另外,请记住以下所有条件:

NULL = 1
NULL <> 1
NULL = NULL
NULL <> NULL

是假的。 所有在一侧具有 NULL 的条件将评估为 false。这是因为 NULL 表示未知值。

如您所见,您的预期完全错误。您似乎希望test1 的第一行与test2 的第一行连接在一起,依此类推。 sql 中没有这样的“魔法”——连接的整个逻辑都放在 ON 子句中,它连接了 1,如前所述。

【讨论】:

  • 你明白我的疑惑。我只是在想只有 test1 的第一行值为 1 才会与 test2 的第一行的值为 1 连接。但这是错误的。它会在其他表中找到所有 1 并加入它。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2017-07-13
  • 2013-01-22
  • 2012-09-29
  • 1970-01-01
相关资源
最近更新 更多