Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL-如何使简单查询更快_Sql_Postgresql - Fatal编程技术网

PostgreSQL-如何使简单查询更快

PostgreSQL-如何使简单查询更快,sql,postgresql,Sql,Postgresql,我有一个600毫秒的查询。 如何改进它-我认为与日期比较的一致性是一个关键 select sensor_id, sum(val) from tests where sensor_id in (34,35) --index on this column and date_trunc('month', audit_date) = date_trunc('month', current_date) group by sensor_id; 您可以使用表达式date\u trunc('month

我有一个600毫秒的查询。 如何改进它-我认为与日期比较的一致性是一个关键

select 
sensor_id,
sum(val) 
from tests 
where 
sensor_id in (34,35) --index on this column
and date_trunc('month', audit_date) = date_trunc('month', current_date)
group by sensor_id;

您可以使用表达式
date\u trunc('month',audit\u date)
SARGable:

select 
   sensor_id,
   sum(val) 
from tests 
where sensor_id in (34,35) --index on this column
  and audit_date >= cast(date_trunc('month', current_date) as date)
  and audit_date < cast(date_trunc('month', current_date) as date)
                   + interval '1 month'
group by sensor_id;

只是为了补充卢卡斯·索兹达的回答,我觉得很好

在无法修改SQL的情况下(出于任何原因),可以在PostgreSQL中创建具有特定列和/或列表达式组合的索引。就你而言:

create index ix1 on tests (sensor_id, date_trunc('month', audit_date));

有了这个索引,您可以原封不动地使用现有的SQL,并获得高性能。

太好了。时间降到45毫秒。我打算提出同样的解决方案,不仅作为一个工人,而且作为一个,在某种程度上。“更好”的解决方案(仅针对这个具体问题):尽管audit_date列上的索引更通用(因为它更可能用于其他查询,所以更可取),但是`date_trunc(…)`上的索引将具有更少的不同键(因此假设它是btree,我猜遍历它的速度会稍微快一些),并且,更重要的是:它将用于测试单个等式,而不是两个不等式(两个条件,一个是revense扫描…)。
create index ix1 on tests (sensor_id, date_trunc('month', audit_date));