提高Master Detail SQL代码性能

时间:2014-08-31 06:34:26

标签: sql

我有两张桌子。

enter image description here

我需要一份报告,其中包含Payment1Payment2列中的名称和付款总额,不会重复。

所以我写这个:

(
  SELECT Pid1, SUM(Payment1) as sum1, COUNT(*) as number, _name
  FROM perform, Person
  WHERE perform.Pid1= Person.id
  GROUP BY _name, Pid1
)
UNION
(
  SELECT Pid2, SUM(Payment2) as sum2, COUNT(*) as number, _name 
  FROM perform, Person
  WHERE perform.Pid2= Person.id
  GROUP BY _name, Pid2
)

输出: Result: 此代码有效,但速度太慢。我怎样才能有更好的表现?

1 个答案:

答案 0 :(得分:1)

您可以通过将person移动到子查询来减少加入union的次数:

select  pers.id
,       perf_sum.sum_payment
,       perf_sum.count_payment
,       pers._name
from    (
        select  pid
        ,       count(*) as count_payment
        ,       sum(payment) as sum_payment
        from    (
                select  PID1 as pid
                ,       Payment1 as payment
                from    perform
                union all
                select  PID2
                ,       Payment2
                from    perform
                ) perf
        group by
                pid
        ) perf_sum
join    person pers
on      perf.pid = pers.id