2011-04-11 97 views
2

我在PostgreSQL 9.0.3数据库中拥有一个简单的表,该数据库包含来自风力涡轮机控制器的轮询数据。每行表示特定时间的特定传感器的值。目前该表有大约90M行:缓慢postgresql查询是否where子句匹配没有行

wtdata=> \d integer_data 
      Table "public.integer_data" 
Column |   Type   | Modifiers 
--------+--------------------------+----------- 
date | timestamp with time zone | not null 
name | character varying(64) | not null 
value | integer     | not null 
Indexes: 
    "integer_data_pkey" PRIMARY KEY, btree (date, name) 
    "integer_data_date_idx" btree (date) 
    "integer_data_name_idx" btree (name) 

一个查询,我需要的是找到最后一次的变量被更新:

select max(date) from integer_data where name = '<name of variable>'; 

此查询工作正常存在的变量进行搜索时在表:

wtdata=> select max(date) from integer_data where name = 'STATUS_OF_OUTPUTS_UINT16'; 
      max   
------------------------ 
2011-04-11 02:01:40-05 
(1 row) 

但是,如果我尝试寻找不存在于表中的变量,查询挂起(或需要更长的时间比我有耐心):

select max(date) from integer_data where name = 'Message'; 

我已经让查询运行了几个小时,有时几天没有结束的迹象。有与NAME =“消息”的表中没有行:

wtdata=> select count(*) from integer_data where name = 'Message'; 
count 
------- 
    0 
(1 row) 

我不明白为什么一个查询快,其他的需要永远。查询以某种方式被强制扫描整个表?

wtdata=> explain select max(date) from integer_data where name = 'Message'; 
                 QUERY PLAN              
------------------------------------------------------------------------------------------------------------------------ 
Result (cost=13.67..13.68 rows=1 width=0) 
    InitPlan 1 (returns $0) 
    -> Limit (cost=0.00..13.67 rows=1 width=8) 
      -> Index Scan Backward using integer_data_pkey on integer_data (cost=0.00..6362849.53 rows=465452 width=8) 
       Index Cond: ((date IS NOT NULL) AND ((name)::text = 'Message'::text)) 
(5 rows) 

下面是一个快速查询的查询计划:

wtdata=> explain select max(date) from integer_data where name = 'STATUS_OF_OUTPUTS_UINT16'; 
                 QUERY PLAN               
-------------------------------------------------------------------------------------------------------------------------- 
Result (cost=4.64..4.65 rows=1 width=0) 
    InitPlan 1 (returns $0) 
    -> Limit (cost=0.00..4.64 rows=1 width=8) 
      -> Index Scan Backward using integer_data_pkey on integer_data (cost=0.00..16988170.38 rows=3659570 width=8) 
       Index Cond: ((date IS NOT NULL) AND ((name)::text = 'STATUS_OF_OUTPUTS_UINT16'::text)) 
(5 rows) 
+0

你在这张桌子上分析过吗? – Kuberchaun 2011-04-11 16:15:18

+0

是的,我手动运行分析,加上autovacuum正在运行。 – jcollie 2011-04-11 16:17:40

+0

你有没有机会在压缩文件中共享你的数据库?看起来像一个很好的学习机会? – Kuberchaun 2011-04-11 16:22:49

回答

1

更改主键(名称,日期)。