使用PostgreSQL中的数组列等条件有效地查询表

Jua*_*oto 5 postgresql indexing performance query-optimization

需要提出一种方法来有效地执行查询,并WHERE使用时间戳列排序的子句中的数组和整数列.使用PostgreSQL 9.2.

我们需要执行的查询是:

SELECT id 
from table 
where integer = <int_value> 
  and <text_value> = any (array_col) 
order by timestamp 
limit 1;
Run Code Online (Sandbox Code Playgroud)

int_value是一个整数值,text_value是一个1-3字母的文本值.

表结构如下:

    Column     |            Type             |       Modifiers
---------------+-----------------------------+------------------------
 id            | text                        | not null
 timestamp     | timestamp without time zone |
 array_col     | text[]                      |
 integer       | integer                     |

我应该如何设计索引/修改查询以使其尽可能高效?

非常感谢!如果需要更多信息,请告诉我,我会尽快更新.

Jak*_*nia 2

PG 可以在数组上使用索引,但您必须使用数组运算符,而不是<text_value> = any (array_col)使用ARRAY[<text_value>]<@array_col/sf/answers/284184981/)。SET enable_seqscan=false;如果可以查看您创建的索引是否有效,您可以使用该命令强制 pg 使用索引。不幸的是,GIN无法在整数列上创建索引,因此您必须为这两列创建两个不同的索引。请参阅此处的执行计划:http://sqlfiddle.com/#!12 /66a71/2