【问题标题】:Combine three tables with join an two with union将三个表与连接结合起来,将两个与联合结合起来
【发布时间】:2021-09-28 16:53:30
【问题描述】:

我想合并三个表。其中两个多列必须连接在一起。

T1

id name
1 Carl
2 Max
3 Bob

t2

id t1_id lastname function
5 1 Johnsen Welder
6 2 Clinten Carpenter
7 3 Brink Mason

t3

id t2-id Function
9 5 Metalworking
10 6 Cabinet maker
11 7 jointer

结果

id name lastname Function
1 Carl Johnsen Welder
1 Carl Johnsen Metalworking
2 Max Clinten Carpenter
2 Max Clinten Cabinet maker
3 Bob Brink Mason
3 Bob Brink jointer

我的代码是

Select t1.id, t1.naam, t2.lastname , t3.Function 
From t1
   left join t2 on t2.t1-id=t1.[id]
   left join t3 on t3.t2-id=t2.[id],
   (Select
        Function
        from t2
        union 
        select
        Function
        from t3)t

【问题讨论】:

    标签: mysql sql join merge union


    【解决方案1】:

    您需要使用子查询加入基于 id 的联合

    Select 
        t1.id, t1.naam, t2.lastname, t.Function 
    From 
        t1
    Left Join 
        t2 On t2.t1 - id = t1.[id]
    Left Join 
        t3 On t3.t2 - id = t2.[id]
    Inner Join 
        (Select id, Function
         From t2
         Union 
         Select id, Function
         From t3) t On t.id = t1.id 
    

    【讨论】:

      【解决方案2】:

      我正在考虑在两个单独的查询上使用union all,一个在两个表上,一个在三个表上:

      select t1.id, t1.name, t2.lastname, t2.function
      from t1 join
           t2
           on t1.id = t2.t1_id
      union all
      select t1.id, t1.name, t2.lastname, t3.function
      from t1 join
           t2
           on t1.id = t2.t1_id join
           t3
           on t2.id = t3.t2_id;
      

      请注意,不需要外连接。我猜这会比union/union all 的选项性能更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 2021-11-23
        • 2019-12-27
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 2020-11-04
        • 2011-12-10
        相关资源
        最近更新 更多