2015-09-23 51 views
0

我有以下查詢這個複雜查詢有多少個索引?

select m.* 
from message_log m 
where m.from_id <> ? 
    and m.to_id = ? 
    and m.unix_timestamp = (select max(unix_timestamp) 
          from message_log 
          where match_id = m.match_id 
          group by match_id) 

這大約需要2分鐘完成。據我所知,提高性能的唯一方法是有索引或更好的硬件。我嘗試了以下幾列

CREATE INDEX message_log_from_id_to_id_match_id_unix_timestamp_idx 
    ON message_log 
    USING btree 
    (from_id COLLATE pg_catalog."default", to_id COLLATE pg_catalog."default", match_id COLLATE pg_catalog."default", unix_timestamp); 

它並沒有改善性能加入「一個」指數。我是否在錯誤的列上創建索引?請推薦我可以做些什麼來提高性能。我使用PostgreSQL 9.1

回答

2

爲了達到最佳效果,我將定義以下2個索引,與這些特定列的訂單:

  • to_id, unix_timestamp, from_id(用於查詢的主要部分)
  • match_id, unix_timestamp(用於subquery)

很難說清楚,因爲我們不知道你的不同列的基數。

+0

哇,它現在在270毫秒內完成! – Arya