在Postgres中使用子查询重构性能缓慢的查询

时间:2018-10-18 14:42:54

标签: postgresql activerecord query-optimization

我的查询执行时间太长(600毫秒)。这主要是由于具有Distinct关键字,如果没有,它将在约20毫秒内执行。我曾尝试将Distinct取出来,并在visit.participation_id上使用了分组依据,但没有看到任何性能改进。这是原始查询:

SELECT COUNT(*) FROM "participations" WHERE "participations"."event_id" = $1 AND "participations"."is_preview" = $2 AND ("participations"."id" NOT IN (SELECT DISTINCT "visits"."participation_id" FROM "visits" INNER JOIN "ahoy_events" ON "ahoy_events"."visit_id" = "visits"."id" WHERE "visits"."event_id" = $3 AND "visits"."participation_id" IN (SELECT "participations"."id" FROM "participations" WHERE "participations"."event_id" = $4 AND "participations"."is_preview" = $5))) 

我已经有关于Visitpartner_id和event_id的索引。

如何将其重构为不使用Distinct操作或可以执行其他操作?在这里使用物化视图是否有意义?

1 个答案:

答案 0 :(得分:1)

您可以使用EXISTS重写它:

SELECT COUNT(*) 
FROM "participations" p2
WHERE p2."event_id" = $1 
   AND p2."is_preview" = $2 
   AND NOT EXISTS (SELECT 1
                   FROM "visits" 
                   JOIN "ahoy_events" ON "ahoy_events"."visit_id" = "visits"."id" 
                   JOIN  "participations" ON "visits"."participation_id" = "participations"."id"
                   WHERE "visits"."event_id" = $3 
                     AND "participations"."event_id" = $4  
                     AND "participations"."is_preview" = $5
                     AND p2."participation_id" = "participations"."id"))