需要想出一种方法来有效地执行查询,其中包含 WHERE
子句中的数组和整数列,按时间戳列排序。使用 PostgreSQL 9.2。
我们需要执行的查询是:
SELECT id
from table
where integer = <int_value>
and <text_value> = any (array_col)
order by timestamp
limit 1;
int_value
是一个整数值,text_value
是一个 1 - 3 个字母的文本值。
表结构是这样的:
Column | Type | Modifiers ---------------+-----------------------------+------------------------ id | text | not null timestamp | timestamp without time zone | array_col | text[] | integer | integer |
我应该如何设计索引/修改查询以使其尽可能高效?
非常感谢!如果需要更多信息,请告诉我,我会尽快更新。
最佳答案
PG 可以在数组上使用索引,但你必须为此使用数组运算符,而不是 <text_value> = any (array_col)
使用 ARRAY[<text_value>]<@array_col
(https://stackoverflow.com/a/4059785/2115135)。您可以使用命令 SET enable_seqscan=false;
如果可以查看您创建的索引是否有效,则强制 pg 使用索引。遗憾GIN
不能在整数列上创建索引,因此您必须为这两列创建两个不同的索引。
在此处查看执行计划:http://sqlfiddle.com/#!12/66a71/2
关于performance - 高效查询PostgreSQL中包含数组列的条件表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504070/