我想在另一个表上使用FULL OUTER JOIN
的结果作为FULL OUTER JOIN
的表格。我应该使用的语法是什么?
例如:T1,T2,T3是我的表,其列号为id,name。我需要这样的东西:
T1 FULL OUTER JOIN T2 on T1.id = T2.id ==> Let this be named X
X FULL OUTER JOIN T3 on X.id = t3.id
我希望实现这一点,以便在最终的ON子句中,我希望T3.id匹配T1.id
或T2.id
。任何替代方法也可以。
答案 0 :(得分:2)
SELECT COALESCE(X.id,t3.id) AS id, *-- specific columns here instead of the *
FROM
(
SELECT COALESCE(t1.id,t2.id) AS id, * -- specific columns here instead of the *
FROM T1 FULL OUTER JOIN T2 on T1.id = T2.id
) AS X
FULL OUTER JOIN T3 on X.id = t3.id
答案 1 :(得分:1)
您可以使用IN()
按照建议进行操作FROM T1
FULL OUTER JOIN T2
ON(T1.id = T2.id)
FULL OUTER JOIN T3
ON(T3.ID IN(T2.id,T1.id))
或者我认为你可以用UNION(取决于你需要的东西)来做:
SELECT * FROM
(SELECT name,id from T1
UNION
SELECT name,id from T2) x
FULL OUTER JOIN T3
ON(t3.id = x.id)
答案 2 :(得分:1)
通常,完全外连接链不会像预期的那样表现。一个替换使用left join
。当表格包含您需要的所有ID时,这种方法效果最佳。但你也可以构建:
from (select id from t1 union
select id from t2 union
select id from t3
) ids left join
t1
on ids.id = t1.id left join
t2
on ids.id = t2.id left join
t3
on ids.id = t3.id
请注意,第一个子查询通常可以由表替换。如果您有这样的表,则可以在where
子句中选择匹配的行:
from ids left join
t1
on ids.id = t1.id left join
t2
on ids.id = t2.id left join
t3
on ids.id = t3.id
where t1.id is not null or t2.id is not null or t3.id is not null