我有一個有近100萬行的漂亮的大桌子,其中一些查詢的時間是long(超過一分鐘)。如何在Postgres中優化此SQL查詢?
這裏是一個多數民衆贊成讓我特別辛苦...
EXPLAIN ANALYZE SELECT "apps".* FROM "apps" WHERE "apps"."kind" = 'software' ORDER BY itunes_release_date DESC, rating_count DESC LIMIT 12;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------
Limit (cost=153823.03..153823.03 rows=12 width=2091) (actual time=162681.166..162681.194 rows=12 loops=1)
-> Sort (cost=153823.03..154234.66 rows=823260 width=2091) (actual time=162681.159..162681.169 rows=12 loops=1)
Sort Key: itunes_release_date, rating_count
Sort Method: top-N heapsort Memory: 48kB
-> Seq Scan on apps (cost=0.00..150048.41 rows=823260 width=2091) (actual time=0.718..161561.149 rows=808554 loops=1)
Filter: (kind = 'software'::text)
Total runtime: 162682.143 ms
(7 rows)
所以,我將如何優化呢? PG版本是9.2.4,FWIW。
kind
和kind, itunes_release_date
已經有索引。
這並不回答你的問題,但如果你有100萬條記錄,你可能最好使用'apps'中的數字引用來創建一個'app_kind'表,而不是重複'varchars',比如''software''超過 –
@LukasEder:或者他可以使用枚舉來保持現有查詢不變。 –