sql - 根据不同的条件在同一个表上多次连接与在聚合表上连接一次

标签 sql sql-server join optimization sql-server-2008-r2

我目前有一个 View ,可以根据相同的条件多次连接表,例如:

Select
m.ID,
a.value as value1,
b.value as value2,
c.value as value3,
d.value as value4

from
main_table m
left join other_table a on m.ID = a.ID and a.X = 'this'
left join other_table b on m.ID = b.ID and b.X = 'that'
left join other table c on m.ID = c.ID and c.X = 'third'
left join other table d on m.ID = d.ID and d.X = 'other'

我想知道合并四个表并聚合它们是否会更有效或更低效,这样我就可以在一个连接中完成所有操作:

Select
m.ID,
value1,
value2,
value3,
value4

from
main_table m
left join (select ID,
           MAX(case X when 'this' then value end) value1,
           MAX(case X when 'that' then value end) value2,
           MAX(case X when 'third' then value end) value3,
           MAX(case X when 'other' then value end) value4
           from ( 
           select ID,X,value from other_table
           where X = 'this'
           union all
           select ID,X,value from other_table
           where X = 'that'
           union all
           select ID,X,value from other_table
           where X = 'third'
           union all
           select ID,X,value from other_table
           where X = 'other')
           GROUP BY ID) AS A
on A.ID = m.ID

我在实验之前询问是因为实际上, View 比这复杂得多,并且需要很长时间才能重写,所以我想确保我没有浪费时间。

基本上,我的问题是执行聚合和group by的成本是否会超过执行这些多个连接的成本。另外,我认为包含此 View 包含许多其他连接(15-20)这一事实是相关的,因此我尝试通过以任何方式减少该数量来进行优化。

编辑 另外,我觉得有必要补充一下,涉及到链接服务器,并且这两个表位于不同的数据库上;我尝试减少连接数量的另一个原因。

任何见解或帮助将不胜感激。

提前致谢。

最佳答案

与大多数性能问题一样,您需要测试系统上数据的不同版本。但是,我认为您想要的聚合查询是:

Select m.ID, value1, value2, value3, value4
from main_table m left join
     (select ID,
             MAX(case X when 'this' then value end) value1,
             MAX(case X when 'that' then value end) value2,
             MAX(case X when 'third' then value end) value3,
             MAX(case X when 'other' then value end) value4
      from other_table
      group by ID
     ) A
     on A.ID = m.ID;

聚合的优点是添加更多值不会对性能产生太大影响。添加新的联接可能会影响性能,因此在某些时候,聚合的性能可能会优于联接。

关于sql - 根据不同的条件在同一个表上多次连接与在聚合表上连接一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992167/

相关文章:

sql - 在sql查询中获取没有添加列的表

c# - 如何在Azure角色中缓存数据库读取?

sql - Microsoft SQL Server 2008 外部备份

SQL 连接条件

php - mysql 中的完整 OUTER JOIN 或 UNION

mysql - 无法使任何 MYSQL Join 语句起作用

mysql - 计算油耗

mysql - SQL:查找每个运行者运行之间的平均天数

python - MySQL 查询参数的数量与传递给执行的参数匹配,但 Python 引发 "not all arguments converted"

mysql - 如果我自然加入这两个表会发生什么?