Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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中max上的谓词高效地查询GROUP BY_Postgresql - Fatal编程技术网

Postgresql 使用postgres中max上的谓词高效地查询GROUP BY

Postgresql 使用postgres中max上的谓词高效地查询GROUP BY,postgresql,Postgresql,鉴于以下数据,我想回答这个问题: 仅从id为的实体的最新状态, 选择id,其中x=9的时间 我们应该返回: id | time --------- 2 | 4 ... 以下查询回答了问题: 选择id、时间 从t 参加 在id、时间上选择DISTINCT 从t 按id排序,时间描述最后为空 最近的 在t.id=most_recent.id和t.time=most_recent.time上 其中x=9 但即使使用这些指数: 创建索引idx_rank ON t id,time DESC NULL

鉴于以下数据,我想回答这个问题:

仅从id为的实体的最新状态, 选择id,其中x=9的时间

我们应该返回:

id | time 
---------
2  | 4
...
以下查询回答了问题:

选择id、时间 从t 参加 在id、时间上选择DISTINCT 从t 按id排序,时间描述最后为空 最近的 在t.id=most_recent.id和t.time=most_recent.time上 其中x=9 但即使使用这些指数:

创建索引idx_rank ON t id,time DESC NULLS LAST; 在tx上创建索引idx_x; 查询速度慢,数据量大,因为它必须加入所有最新的id,次

将谓词放入两次可加快查询速度:

选择id、时间 从t 参加 在id、时间上选择DISTINCT 从t 参加 选择t.id 从t 其中x=9 作为内滤波器 ON t.id=内部过滤器id 按t.id排序,t.time DESC最后为空 最近的 在t.id=most_recent.id和t.time=most_recent.time上 其中x=9 但感觉真的很难看,特别是对于涉及连接等更复杂的谓词,还有其他方法吗

id | time 
---------
2  | 4
...
 Merge Join
   Merge Cond: t.id = most_recent.id AND t.time = most_recent.time
   ->  Unique  
         ->  Index Only Scan using idx_rank
   ->  Sort
         Sort Key: t.id, t.time DESC NULLS LAST
         ->  Index Scan using idx_x on t
               Index Cond: x = 9