【问题标题】:confused with result of joining the same table multiple times与多次加入同一个表的结果相混淆
【发布时间】:2013-04-29 06:01:11
【问题描述】:

我有 2 张桌子(请参阅 http://sqlfiddle.com/#!3/6d04f/20

我很难想象以下两者之间的区别:

select *
from TableA as a right outer join tableB as b on b.city1id = a.id

select *
from TableA as a right outer join tableB as b on b.city1id = a.id
left outer join tableB parent on parent.city2id = b.city1id

TableA 和 TableB 之间的右外连接向下,结果再次与 TableB 左外连接。

运行这两个查询的结果是相同的,所以我不确定左外连接在这种情况下会产生什么影响。

从概念上讲,我不确定这里有什么区别。

【问题讨论】:

    标签: sql-server join


    【解决方案1】:

    好的,我会解释as i wrote that

    查询 2

     select *
        from TableA as a right outer join tableB as b on b.city1id = a.id
        left outer join tableB parent on parent.city2id = b.city1id
    

    您可以像这样重写该查询

    select *
    from Tableb as b left outer join tablea as a on b.city1id = a.id
    left  outer join tableb parent on parent.city2id = b.city1id
    

    tableB 和 table A 之间的第一个左外连接就是这样做的

    TableB( get all records ) and tableA matching records = call this result set as T
    

    T 和 tableb 之间的第二个左外连接就是这样做的

    T ( get all records ) and tableb matching records
    

    see here

    查询 1

    select *
    from TableA as a right outer join tableB as b on b.city1id = a.id
    

    可以这样写

    select *
    from Tableb as b left outer join tablea as a on b.city1id = a.id
    

    它只是这样做

    tableB 和 table A 之间的第一个左外连接(在上一个查询中进行了解释)

     TableB( get all records ) and tableA matching records 
    

    【讨论】:

    • 谢谢。这是一个很好的解释。唯一让我感到困惑的是设置 T 和 T (get all records) and tableb matching records 的结果在这种情况下似乎是同一件事 - 不是吗?看看这两种情况下的查询结果。也许,我忽略了一些东西?我感谢您的帮助。谢谢。
    【解决方案2】:

    这里真正的问题是:你的目标是什么。外连接只是意味着提到的一侧(左侧或右侧)是要从中提取记录的一侧,然后另一侧将提取匹配的记录,如果没有找到这样的匹配项,则返回 null。

    由于您拥有A right B left (B as parent),因此两个连接都将从B 中提取记录,而表A 只会根据需要提取匹配项或空值。因此,您的核心查询是所有表 B,在您进行匹配时将表 A 拉入,最后在找到匹配项时将 B as parent 拉入。

    因此,这两个查询都将拉表B 作为响应的核心,而表B 控制返回的行数:B 的所有行。在您的 Fiddle 中,这是 7 行。

    (外连接可能返回更多行而不是主表(因为可选侧的多条记录匹配单个所需的侧记录),但绝不会少于所需的表) .

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 1970-01-01
      • 2017-09-28
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      相关资源
      最近更新 更多