我有一个运行中的PostgreSQL查询,但是要花费大量时间才能执行。我需要帮助对其进行优化。
我有:
with
查询,该查询从头开始获取所需数据我需要帮助来优化此查询
with data as (
select
e.id,
e.name,
t.barcode,
tt.variant,
t.cost_cents::decimal / 100 as ticket_cost,
t.fee_cents::decimal / 100 as booking_fee
from
tickets t
inner join events e on t.event_id = e.id
inner join ticket_types tt on t.ticket_type_id = tt.id
where
t.status = 2
and e.source in ('source1', 'source2')
)
select
d.name,
count(distinct d.barcode) as issued,
(select count(distinct d2.barcode) from data d2 where d2.id = d.id and d2.variant is null) as sold,
sum(d.ticket_cost) as ticket_revenue,
sum(d.booking_fee) as booking_fees
from
data d
group by
id,
name
答案 0 :(得分:0)
使用EXPLAIN更好地检测慢速零件。 它将显示所有零件的成本
答案 1 :(得分:0)
您可以通过创建适当的索引来加快联接速度。
此外,删除子查询
(select count(distinct d2.barcode) from data d2 where d2.id = d.id and d2.variant is null)
从SELECT子句中添加到d2表的联接,如下所示:
select
d.name,
count(distinct d.barcode) as issued,
count(distinct d2.barcode) as sold,
sum(d.ticket_cost) as ticket_revenue,
sum(d.booking_fee) as booking_fees
from
data d
left join data d2 on (d2.id = d.id and d2.variant is null)
group by
d.id,
d.name