多个完全外部联接

mqkwyuun  于 2021-06-26  发布在  Impala
关注(0)|答案(3)|浏览(400)

我想用 FULL OUTER JOIN 作为一张table FULL OUTER JOIN 在另一张table上。我应该使用什么语法?
例如: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 . 任何其他方法也可以。

igsr9ssn

igsr9ssn1#

你可以按照你的建议去做,使用in()

FROM T1
FULL OUTER JOIN T2
 ON(T1.id = T2.id)
FULL OUTER JOIN T3
 ON(T3.ID IN(T2.id,T1.id))

或者我认为你可以通过工会来做到这一点(取决于你需要什么):

SELECT * FROM 
    (SELECT name,id from T1
    UNION
    SELECT name,id from T2) x
FULL OUTER JOIN T3
   ON(t3.id = x.id)
neekobn8

neekobn82#

通常,完全外部连接的链的行为与预期不完全相同。一个替代品使用 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
kr98yfug

kr98yfug3#

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

相关问题