首页 > 解决方案 > 有没有更好的方法将多个列值从表连接到另一个?

问题描述

我有一个这样的表(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

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

标签: sqlsql-server

解决方案


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

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).


推荐阅读