如何优化这个缓慢的PostgreSQL查询

时间:2014-06-13 15:05:23

标签: sql postgresql optimization

我已经跟踪了SQL查询缓慢的API端点的原因,并且在我的生活中无法优化它。

查询如下:

SELECT "Views".*, "Show".*, "Episode".*, "User".* FROM "Views"
LEFT OUTER JOIN "Shows" AS "Show" ON "Show"."id" = "Views"."ShowId"
LEFT OUTER JOIN "Episodes" AS "Episode" ON "Episode"."id" = "Views"."EpisodeId"
LEFT OUTER JOIN "Users" AS "User" ON "User"."id" = "Views"."UserId"
WHERE "Show"."tvdb_id" IN (259063,82066,258823,265766,261742,82283,205281,182061,121361)
AND "User"."id"=29;

完成需要3000-4200毫秒。可以在此处找到查询的EXPLAIN ANALYZE结果:http://explain.depesz.com/s/J9R

编辑:我也尝试将IN()分成OR:

SELECT "Views".*, "Show".*, "Episode".*, "User".* FROM "Views"
LEFT OUTER JOIN "Shows" AS "Show" ON "Show"."id" = "Views"."ShowId"
LEFT OUTER JOIN "Episodes" AS "Episode" ON "Episode"."id" = "Views"."EpisodeId"
LEFT OUTER JOIN "Users" AS "User" ON "User"."id" = "Views"."UserId"
WHERE
    "Show"."tvdb_id"=259063 OR
    "Show"."tvdb_id"=82066 OR
    "Show"."tvdb_id"=258823 OR
    "Show"."tvdb_id"=265766 OR
    "Show"."tvdb_id"=261742 OR
    "Show"."tvdb_id"=82283 OR
    "Show"."tvdb_id"=205281 OR
    "Show"."tvdb_id"=182061 OR
    "Show"."tvdb_id"=121361 
AND "User"."id"=29; 

我尝试在LEFT OUTER JOIN中引用的列上创建索引,但这会导致边际收益(如果有的话)。有趣的是我还尝试将WHERE x IN缩减为单个WHERE x = y,这会立即改善情况,而是在200-300毫秒内做出响应。那么我将如何优化IN语句?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试在字段ShowId,EpisodeId,UserId上的表视图上组合索引。

CREATE INDEX Views_idx ON Views
  USING btree (ShowId, EpisodeId, UserId);

PS。解释链接错误,这是其他一些查询

致以最诚挚的问候,

NELE