我有两张桌子。
我需要一份报告,其中包含Payment1
,Payment2
列中的名称和付款总额,不会重复。
所以我写这个:
(
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
)
输出: 此代码有效,但速度太慢。我怎样才能有更好的表现?
答案 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