sql - 有没有更好的方法将多个列值从表连接到另一个?
问题描述
我有一个这样的表(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
这是可行的,但我觉得有比做一堆连接更好的方法。有什么我遗漏的东西可以让这个更干净、更快吗?
解决方案
你的方法很好。另一种方法是条件聚合:
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)
.
推荐阅读
- elasticsearch - Elasticsearch:查询时的自定义分析器
- python - 如何从属性内部获取类名(这又是某种类型的对象)
- selenium - 这是否可以通过数据操作将描述操作为具有相同含义但不同的单词
- java - 什么是Java中与异步API接口的良好设计模式
- javascript - 使用 Dates 对象时循环未按预期运行
- python - 如何通过 docx 库或 xml 将单元格文本包装在表格中?
- xcode - React Native App - Xcode 中的名称更改 - 不再运行 ' ***App 尚未注册
- wordpress - 如何在 cf7 电子邮件中显示不同的消息?
- mqtt - 订阅配置文件中的多个级别的主题?
- php - 提供默认文件的 Google App Engine 服务