gpt4 book ai didi

postgresql - 如果 where 子句不匹配任何行,则 postgresql 查询缓慢

转载 作者:行者123 更新时间:2023-11-29 12:22:47 25 4
gpt4 key购买 nike

我在 PostgreSQL 9.0.3 数据库中有一个简单的表,用于保存从风力涡轮机 Controller 轮询的数据。每行代表特定传感器在特定时间的值。目前该表有大约 9000 万行:

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 = 'Message' 的行:

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)

最佳答案

将主键更改为(姓名,日期)。

关于postgresql - 如果 where 子句不匹配任何行,则 postgresql 查询缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5623353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com