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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.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 如何索引此postgres表以允许通过'id'查询进行有效的最小(时间)分组?_Postgresql_Indexing - Fatal编程技术网

Postgresql 如何索引此postgres表以允许通过'id'查询进行有效的最小(时间)分组?

Postgresql 如何索引此postgres表以允许通过'id'查询进行有效的最小(时间)分组?,postgresql,indexing,Postgresql,Indexing,我想获得给定id的最早时间。因此,对于此表: table | id | time | |----|------| | a1 | t1 | | a1 | t2 | | a1 | t3 | | a2 | t4 | | a3 | t5 | | a3 | t6 | 其中,对于每个id,time按升序排列,我想要: | id | time | |----|------| | a1 | t1 | | a2 | t4 | | a3 | t5 | 我希望最终运行此查询:

我想获得给定id的最早时间。因此,对于此表:

table
| id | time |
|----|------|
| a1 | t1   |
| a1 | t2   |
| a1 | t3   |
| a2 | t4   |
| a3 | t5   |
| a3 | t6   |
其中,对于每个
id
time
按升序排列,我想要:

| id | time |
|----|------|
| a1 | t1   |
| a2 | t4   |
| a3 | t5   |
我希望最终运行此查询:

SELECT MIN(time) as earliestTime, table."id" FROM table
WHERE table."id" IN %s 
GROUP BY table."id";
其中
%s
id
s的大数组。但是,
可能非常大

为了加快速度,我尝试为此列创建索引:

create index stream_time on table using btree ("id" ASC, "time" ASC);

但我不确定这是否是实现我目标的最有效方式。有人能告诉我吗?

没有索引可以加速此查询,它总是需要顺序扫描


如果没有太多的组,则可以使用递归查询更快地获得结果。

我觉得您的索引非常好,我想不出更好的方法来使用。您不需要引用
id
。索引很好,但是如果%s是一个非常大的id数组,最好在包含这些id的values子句上加入,或者将%s作为实际的postgres数组传入,并执行类似于
join unnest(%s)的操作,如id=x上的u(x)
请显示解释(分析,缓冲区)使用现有索引创建一个实际大小的查询。```查询计划--------------------------------------------------------------------------------------------------------------------------------HashAggregate(cost=812801.67..812889.57 rows=8790 width=49)(实际时间=50887.052..50901.141行=17413循环=1)组键:“id”->数据扫描顺序(成本=0.00..659623.78行=30635578宽度=49)(实际时间=0.131..18788.560行=30632802循环=1)计划时间:1.250毫秒执行时间:50906.833毫秒```@jjanes