简体   繁体   中英

How can I optimise this slow PostgreSQL query

I have tracked the cause of a slow API endpoint to an SQL query and cannot for the life of me optimise it.

The query is as follows:

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;

It takes between 3000-4200ms to complete. The result of an EXPLAIN ANALYZE on the query can be found here: http://explain.depesz.com/s/J9R

EDIT: I have also tried separating the IN() into ORs:

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; 

I have tried creating indexes on the columns referenced in the LEFT OUTER JOIN but that resulted in marginal gains (if anything). What's interesting is I also tried reducing the WHERE x IN to a single WHERE x = y and this instantly improved the situation, responding instead in 200-300ms. So how would I go about optimizing the IN statement?

Thanks!

Try to make combined index on table Views on fields ShowId, EpisodeId, UserId together.

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

ps. explain link is wrong, it's for some other query

Best regards,

nele

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM