PostgreSQL 中元组数组的高效 SELECT

hun*_*ter 6 postgresql performance postgresql-performance

records假设我有一个具有以下结构的表

  • id(唯一的整数)
  • 更新(时间戳)

我有一个input_array价值观[[id_1, timestamp_1], [id_4, timestamp_4], ...]。我将每个元素称为tuple_1tuple_4等。

我正在寻找最有效的查询(在 PostgreSQL v11.2+ 中)来选择[id_1, id_4, ...]from records,但仅限于 where tuple_{n}.updated > row{n}.updated。假设input_array可能包含数千个元组和records超过一百万行。

我什至不知道从哪里开始。Lateral join我想到了,unnest以及where in,但到目前为止我尝试过的一切都惨败

更新我愿意input_array采用任何格式(元组,两个单独的数组,等等),并且updated成为int

小智 11

如果您不固定于数组输入,则可以使用元组比较。

select *
from records
where (id, updated) in ( (1, timestamp '2019-01-01 00:00:00'),
                         (2, timestamp '2019-01-02 00:00:00') )
Run Code Online (Sandbox Code Playgroud)

这可以利用常规的 btree 索引(id, updated)

请注意,这适用=两个值,相当于

where (id = 1 and updated = timestamp '2019-01-01 00:00:00')
   or (id = 2 and updated = timestamp '2019-01-02 00:00:00')
Run Code Online (Sandbox Code Playgroud)

但您想使用 来比较时间戳>。如果您加入反对条款,则可以这样做values

select r.*
from records r
  join (
    values 
       (1, timestamp '2019-01-01 00:00:00'),
       (2, timestamp '2019-01-02 00:00:00') 
  ) as t(id,upd) on  r.id = t.id
where r.updated > t.upd;
Run Code Online (Sandbox Code Playgroud)

在线示例: https: //rextester.com/GGC83046