我目前有一个视图,该视图按相同条件多次联接表,例如:

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


我在进行实验之前先询问,因为实际上,视图要复杂得多,并且需要很长时间才能重写,因此我想确保自己不会浪费时间。

基本上,我的问题是执行聚合和group by的成本是否会超过执行这些多个联接的成本。另外,我认为包括该视图包含许多其他联接(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/

10-10 05:38