0

我已经看到这个查询各种 personid 和不同类型的时间不到 10 毫秒,我还看到它需要 16 分钟。到底是怎么回事?

    Column    |       Type       |                       Modifiers
--------------+------------------+--------------------------------------------------------
 id           | bigint           | not null default nextval('record_seq'::regclass)
 type         | integer          | not null
 personid     | integer          |
 reporttime   | bigint           | not null
 totalreading | double precision | not null
 delta        | double precision | not null

Indexes:
    "record_pkey" PRIMARY KEY, btree (id)
    "record_personid_idx" btree (personid)
    "record_type_idx" btree (type)
    "record_reporttime_idx" btree (reporttime) CLUSTER

这是对有时非常慢的查询的解释分析。

explain analyze SELECT ID, TYPE, REPORTTIME, TOTALREADING, DELTA, PERSONID FROM RECORD WHERE PERSONID=1103 AND TYPE=405 AND REPORTTIME <= 1332447354000 ORDER BY REPORTTIME DESC LIMIT 1;

 Limit  (cost=0.00..327.93 rows=1 width=52) (actual time=239749.274..239749.274 rows=0 loops=1)
   ->  Index Scan Backward using record_reporttime_idx on record  (cost=0.00..1196290.82 rows=3648 width=52) (actual time=239749.251..239749.251 rows=0 loops=1)
         Index Cond: (reporttime <= 1332447354000::bigint)
         Filter: ((personid = 1103) AND (type = 405))
 Total runtime: 239749.409 ms

大约有 10-20 种类型,其中 2 种使用最频繁,405 几乎没有使用频率。

 select count(*) from record;
  count
----------
 30420232

 SELECT COUNT(*) FROM record WHERE PERSONID=1103 AND TYPE=405;
  count
-------
    58
4

1 回答 1

1

因为您正在搜索某个目标之前的最后一个报告时间值,所以规划者认为向后搜索是有意义的。

它可能在某些/大部分时间都在起作用,但有时您必须走很长一段路才能找到(personid,type)的正确组合。

如果您通常在 (personid,type) 上搜索,请尝试在两者上或什至所有三列上的组合索引。三列的顺序以及是否需要保留其他索引将取决于您的总查询组合。

于 2012-03-23T09:20:01.537 回答