如何有效地重复查询组中的最新密钥?

时间:2017-10-24 19:30:32

标签: postgresql greatest-n-per-group

我在"事件采购中组织了数TB的数据"样式。对密钥的每次更新都存储在" time"更新,称为级别。内部查询在特定时间或之前查找所有键的最新值。然后外部查询选择特定键。

我将在特定时间(通常是过去)中运行此查询100次,但对于许多键。 有没有办法缓存内部查询,所以只重复运行外部查询?或者有更好的方法来编写此查询吗?

select value from storage 
where lvl = (select max(lvl) from storage as s1 
              where s1.key = storage.key and s1.lvl <= 4)
and key = 'd';

这是表格:

LVL   KEY  VALUE
1     a    10
1     b    11
1     c    12
1     d    13
2     a    20
2     b    21
3     c    32
4     b    41

表格:

create table storage (
    lvl integer,
    key text,
    value text,
    primary key (key, lvl)
) ;

1 个答案:

答案 0 :(得分:0)

一些可能的解决方案是:

--Using CTE to create a temporary table max_storage 
WITH max_storage AS (
    select max(time), key from storage as s1 
              where s1.time <= 4 GROUP BY key
)
SELECT s.value FROM storage s JOIN max_storage m ON (s.time = m.time AND s.key = m.key);

--Simpler solution using DISTINCT ON but not using "cache" as you asked
SELECT DISTINCT ON (key) value FROM storage AS s1 WHERE s1.time <= 4 ORDER BY key, time DESC;

时间和关键列是否已编入索引?如果没有,这样做可能是个好主意。 也不要在对象中使用保留字。

有关CTE hereDISTINCT ON here的更多信息。