【发布时间】:2015-01-19 13:28:58
【问题描述】:
我有一个看起来像这样的表格(每个表格中的行数示例以获得配给的种类):
预期报告节点数(1 000 000 行):
nodejoinkey | integer | not null
nodeid | text | not null
nodeconfigids | text[] |
nodeconfigids 数组一般包含 1-50 个值。
还有第二张桌子:
expectedreports(10 000 行):
pkid | integer | not null
nodejoinkey| integer | not null
...
我想查询所有预期的报告,它们在nodeexpectedreports 中存在一个具有给定nodeConfigId 的条目。
我可能有大量的nodeConfigIds(千)。
什么是最有效的方法?
现在,我有:
select E.pkid, E.nodejoinkey from expectedreports E
inner join (
select NN.nodejoinkey, NN.nodeid, NN.nodeconfigids from (
select N.nodejoinkey, N.nodeid, unnest(N.nodeconfigids) as nodeconfigids
from expectedreportsnodes N
) as NN
where NN.nodeconfigids) IN( VALUES ('cf1'), ('cf2'), ..., ('cf1000'), ..., ('cfN') )
) as NNN on E.nodejoinkey = NNN.nodejoinkey;
这似乎给出了预期的结果,但需要很长时间才能执行。
可以做些什么来改进查询?
更新:
- 数组重叠和索引的建议答案在我的设置中效率大大降低。我说不出为什么。
- 以下版本似乎是最快的(再次说明一下,为什么 - 也许是因为我在 nodeconfigids 中的值通常很少?):
_
select E.pkid, E.nodejoinkey from expectedreports E
inner join (
select NN.nodejoinkey, NN.nodeconfigids
from (
select N.nodejoinkey, N.nodeconfigids,
generate_subscripts(N.nodeconfigids,1) as v
from expectedreportsnodes N
) as NN
where NN.nodeconfigids[v] in(values ('cf1'), ('cf2'), ..., ('cf1000'), ..., ('cfN') )
) as NNN
on E.nodejoinkey = NNN.nodejoinkey
【问题讨论】:
-
为了优化性能,我们一般需要更具体的数据。考虑tag info for
[postgresql-performance]。 -
顺便说一句,您的
IN (VALUES ...)表达式语法无效。您正在混合行和设置语法。 -
@ErwinBrandstetter:感谢语法评论,现在更正
-
使用
IN时不需要values关键字,只需使用in ('cf1', 'cf2', ...) -
@a_horse_with_no_name:我读到使用大量值会更好:postgres.cz/wiki/…。一般是假的吗? (我需要替补)
标签: arrays performance postgresql indexing postgresql-performance