这个简单的查询怎么能花这么长时间?

时间:2014-09-25 11:22:39

标签: postgresql

=> SELECT * FROM "tags" WHERE ("kind" = 'View') ORDER BY "name";
Time: 278.318 ms

标签表包含358行。所有这些都是目前的观点。

   Column    |           Type           |              Modifiers
-------------+--------------------------+-------------------------------------
 id          | uuid                     | not null default uuid_generate_v4()
 name        | text                     | not null
 slug        | text                     | not null
 kind        | text                     | not null
 external_id | text                     |
 created_at  | timestamp with time zone | not null default now()
 updated_at  | timestamp with time zone |
 filter      | json                     |
Indexes:
    "tags_pkey" PRIMARY KEY, btree (id)
    "tags_kind_index" btree (kind)
    "tags_name_index" btree (name)

分析说:

                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------
 Sort  (cost=9.29..9.47 rows=358 width=124) (actual time=0.654..0.696 rows=358 loops=1)
   Sort Key: name
   Sort Method: quicksort  Memory: 75kB
   ->  Seq Scan on tags  (cost=0.00..6.25 rows=358 width=124) (actual time=0.006..0.108 rows=358 loops=1)
         Filter: (kind = 'View'::text)
 Total runtime: 0.756 ms
(6 rows)

1 个答案:

答案 0 :(得分:0)

你运行analyze tags了吗?它将更新表的统计信息。

首先,如果所有kind值都是'view',则该列上的索引无效。只有当列cardinality为高时,才会使用该索引,否则在表格上进行顺序扫描会更便宜。

其次只有358行,无论如何都要做顺序扫描更便宜。