三个表之间的完全外部联接

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

我有三个表,我们可以将它们称为“ 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”解决方案,但我无法使其正常工作。我猜在那里,我不知道如何正确使用多个属性来正确进行连接。

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

sql-server outer-join multiple-tables
1个回答
0
投票

[突然之间,我意识到我没有尝试过的“ 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”函数,如果它可能会产生在大型数据结构/数据集中很难发现的错误,我将不胜感激。 。我现在只尝试了一个看起来工作正常的小样本。但是,当我在大型数据集上运行结果时,我将无法从各个方面验证结果。 :)

© www.soinside.com 2019 - 2024. All rights reserved.