【问题标题】:Full outer join between three tables三个表之间的全外连接
【发布时间】:2020-02-26 18:37:44
【问题描述】:

我有三个表,我们可以称它们为“t1”、“t2”和“t3”,我需要加入它们。我想在两个属性上匹配它们,我们称它们为“Attr1”和“Attr2”,并保留所有三个表中的所有元组,无论它们是否匹配。所有表中的元组在其他表中都没有匹配(多数),并且有一些元组在其他表中的一个或另一个中匹配,并且有少数(大约所有元组的 1%)三个表)在每个表中都有匹配的元组。

我已经尝试了以下解决方案:

select Attr1 = case 
when a.Attr1 is null and b.Attr1 is null then c.Attr1
when a.Attr1 is null and c.Attr1 is null then b.Attr1
when c.Attr1 is null and b.Attr1 is null then a.Attr1
when a.Attr1 is null and b.Attr1 is not null and c.Attr1 is not null then c.Attr1
when c.Attr1 is null and b.Attr1 is not null and a.Attr1 is not null then b.Attr1
when b.Attr1 is null and b.Attr1 is not null and c.Attr1 is not null then a.Attr1
else a.Attr1
end, Attr2 = /*Same principle for Attr2 as used for Attr1*/, other variables
from t1 a
full outer join t2 b on a.Attr1 = b.Attr1 and a.Attr2 = b.Attr2
full outer join t3 c on (a.Attr1 = c.Attr1 and a.Attr2 = c.Attr2) and (b.Attr1 = c.Attr1 and b.Attr2 = c.Attr2)

脚本运行没有错误,但最后一个连接不起作用。 t3和t2之间的匹配似乎失败了。它适用于 t3 和 t1 之间的匹配。

我也尝试了 Serge 在Multiple FULL OUTER JOIN on multiple tables 建议的“isnull”解决方案,但我无法让它发挥作用。在那里我猜我不知道如何正确使用多个属性来连接。

我考虑过的一个解决方案是将连接分成两部分,这样我就可以在一个完全外连接中获得两个表之间的完全外连接。但如果可能的话,我真的想避免这种情况,因为脚本比这里显示的要大得多。而且我很难让逻辑以这种方式顺利运行。

【问题讨论】:

  • 你能联合所有 3 个查询,然后从结果集中进行选择吗?或者对于从哪个表返回哪个属性需要某种层次结构?
  • 感谢您的回复。但按照你说的方式,我有几个不同的层次结构。

标签: sql-server outer-join multiple-tables


【解决方案1】:

突然间,我意识到我没有尝试过的“isnull”解决方案有一种方法,它似乎有效:

from t1 a
full outer join t2 b on a.attr1 = b.attr1 and a.attr2 = b.attr2
full outer join t3 c on isnull(a.attr1,b.attr1) = c.attr1 and isnull(a.attr2,b.attr2) = c.attr2

但是,由于这是我第一次以这种方式(在连接中)使用“isnull”函数,如果 cmets 可能会产生在大数据结构/数据中难以发现的错误,我将不胜感激套。我现在只尝试了一个小样本,看起来它正在工作。但是当我在大数据集上运行它时,我将无法验证各个方面的结果。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2016-03-22
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多