postgresql 在Postgres中搜索整数数组

kx1ctssn  于 2023-02-15  发布在  PostgreSQL
关注(0)|答案(3)|浏览(180)

在Postgres的integer[]列中搜索某个值还有其他方法吗?
我当前安装的Postgres版本 * 不 * 允许以下语句:

SELECT * FROM table WHERE values *= 10;

数组示例:

'{11043,10859,10860,10710,10860,10877,10895,11251}'
'{11311,10698,10697,10710,10712,10711,10708}'

语句应返回数组包含'10710'的每一行。

ahy6op9u

ahy6op9u1#

对于相等性检查,您只需:

SELECT * FROM tbl WHERE 10 = ANY (values);

阅读手册中的ANY/SOME。
对于大表/大数组,考虑使用索引支持的数组运算符,例如:

SELECT * FROM tbl WHERE values @> '{10}'::int[];

参见:

      • 检查Postgres数组中是否存在值**
  • PostgreSQL中的IN与ANY运算符

对于整数数组,考虑附加模块intarray

  • 比较数组是否相等,忽略元素顺序

相关:

  • PostgreSQL可以索引数组列吗?
  • 检查Postgres数组中是否存在值
cbjzeqam

cbjzeqam2#

快速搜索将是如此,但你应该使用索引gist或gin为intarray类型Postgres intarray

SELECT * FROM table WHERE values @> ARRAY[10];
inb24sb2

inb24sb23#

**Store Integer Array as Strings in Postgresql and Query the Array**    
Finally I could save the integer as string array in one column able to successfully convert into array and query the array using below example.

    CREATE TABLE test
    (
      year character varying,
      id serial NOT NULL,
      category_id character varying,
      CONSTRAINT test_pkey PRIMARY KEY (id)
    )

    Data
    "2005";1;"1,2,3,4"
    "2006";2;"2,3,5,6"
    "2006";3;"4,3,5,6"
    "2007";7;"1,2"

    select distinct(id) from test, (select id as cid, unnest(string_to_array(category_id ,  ',')::integer[]) as cat from test) c where c.cid=test.id and cat in (1,2,3);

    Result:
    2
    1
    3
    7

相关问题