使用 ANY 运算符:
where 1 = ANY (array_column)
这将返回所有行array_column
包含值1
至少一次。如果您想检查多个值,请参阅 Clodoaldo 的答案。
如果您在该列上创建索引,这应该非常快。像这样的东西:
create index on the_table using gin (the_array_column);
以下内容受到此处所示解决方案的启发:查找 PostgreSQL 数组中值的位置 https://stackoverflow.com/questions/8798055
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 将减少只需要对实际包含该值的行执行的总工作量。然后,外部查询将“分解”数组以获取值的索引。但使用链接问题中显示的功能实际上可能正是您所追求的。