gpt4 book ai didi

postgresql - 在 postgresql 中搜索没有循环的数组中的元素

转载 作者:行者123 更新时间:2023-11-29 12:21:40 26 4
gpt4 key购买 nike

我正在编写查询以搜索数组中的元素。使用“for”循环搜索效率不高,因为我的数组有很多元素。因此,查询需要花费大量时间来执行。那么谁能说出如何在没有“for”循环的情况下搜索数组中的元素应该更快。我必须得到搜索索引

谢谢,卡西卡

最佳答案

使用 ANY 运算符:

where 1 = ANY (array_column) 

这将返回 array_column 至少一次包含值 1 的所有行。如果您想检查多个值,请参阅 Clodoaldo 的回答。

如果您在该列上创建索引,这应该非常快。像这样:

create index on the_table using gin (the_array_column);

以下内容的灵感来自此处显示的解决方案:Finding the position of a value in PostgreSQL arrays

with sample_data (pk_column, array_data) as (
values
(1, array[1,2,3,4,5]),
(2, array[7,8,9,11]),
(3, array[5,4,3,2,1]),
(4, array[10,9,8,1,4,6]),
(5, array[7,8,9])
)
select *
from (
select pk_column,
unnest(array_data) as value,
generate_subscripts(array_data, 1) as array_index
from sample_data
where 1 = any(array_data)
) t
where value = 1

内部 where 会将需要完成的总工作减少到仅实际包含该值的那些行。然后外部查询将“分解”数组以获取值的索引。但是使用链接问题中显示的功能可能实际上就是您所追求的。

关于postgresql - 在 postgresql 中搜索没有循环的数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18763960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com