【问题标题】:Search in integer array in Postgres在 Postgres 中搜索整数数组
【发布时间】:2012-01-04 18:31:27
【问题描述】:

有没有其他方法可以在 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' 的每一行。

【问题讨论】:

    标签: sql arrays postgresql


    【解决方案1】:
    **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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        对于相等性检查,您可以简单地:

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

        了解ANY/SOME in the manual

        【讨论】:

          猜你喜欢
          • 2021-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-11
          • 1970-01-01
          • 2013-03-01
          • 1970-01-01
          • 2018-08-09
          相关资源
          最近更新 更多