【问题标题】:Is there a better way to join multiple column values from table to another? [duplicate]有没有更好的方法将多个列值从表连接到另一个? [复制]
【发布时间】:2019-11-27 00:30:17
【问题描述】:

我有一张这样的表(table2):

   JoinID ID Value
   1234     1  101
   1234     2  102
   1234     3  103
   1234     4  104

我想将它加入另一个表 (table1),所以我有一行具有特定 ID 作为列,例如:

JoinID ID_1 ID_2 ID_3 OtherStuffFromOthertables
1234   101  102  103  123456789

我目前正在通过这样的多个连接来做到这一点:

LEFT JOIN table2 t2 ON t2.JoinID = t1.JoinID and ID = 1
LEFT JOIN table2 t3 ON t3.JoinID = t1.JoinID and ID = 2
LEFT JOIN table2 t4 ON t4.JoinID = t1.JoinID and ID = 3

这是可行的,但我觉得有比做一堆连接更好的方法。有什么我想念的东西可以让这个更干净、更快吗?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    你的方法很好。另一种方法是条件聚合:

    select t1.JoinId,
           max(case when t2.id = 1 then t2.value end) as value_1,
           max(case when t2.id = 2 then t2.value end) as value_2,
           max(case when t2.id = 3 then t2.value end) as value_3
    from table1 t1 left join
         table2 t2
         on t2.JoinID = t1.JoinId
    group by t1.JoinId;
    

    随着列数的增加,这将具有更好的性能(通常)。但是,如果性能是一个问题,您可能想看看哪个更好。

    实际上,在 SQL Server 中,性能最好的可能是使用outer apply 的混合:

    select t1.JoinId, t2.*
    from table1 t1 outer apply
         (select max(case when t2.id = 1 then t2.value end) as value_1,
                 max(case when t2.id = 2 then t2.value end) as value_2,
                 max(case when t2.id = 3 then t2.value end) as value_3
          from table2 t2
          where t2.JoinID = t1.JoinId
         ) t2;
    

    这避免了对完整数据的聚合——选择每行较小的聚合。它也只引用table2 一次,可以最大限度地利用table2(JoinId, id, value) 上的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多