【发布时间】: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