如果在postgres中的数组中找到值,则如何返回行

时间:2016-01-12 13:56:57

标签: arrays json postgresql

{
    actName: null,
    applicable: {
      applicable: [ 5, 4, 1 ]
  },
   status: 1,
   id: 2
}
{
    actName: null,
    applicable: {
      applicable: [ 3, 2 ]
  },
   status: 1,
   id: 1
}

是否可以在数组中查找值,例如,如果我在2数组中搜索整数值applicable,则返回id为1的行。

3 个答案:

答案 0 :(得分:0)

with t(j) as (values
    ('{
        "actName": null,
        "applicable": {
            "applicable": [ 5, 4, 1 ]
        },
        "status": 1,
        "id": 2
    }'::jsonb),
    ('{
        "actName": null,
        "applicable": {
            "applicable": [ 3, 2 ]
        },
        "status": 1,
        "id": 1
    }')
)
select j ->> 'id' as id
from t
where exists (
    select 1
    from jsonb_array_elements_text(j -> 'applicable' -> 'applicable') s(i)
    where i = '2'
)
;
 id 
----
 1

答案 1 :(得分:0)

此处假设您的数据库中包含jsonb数组json文档,查询可能如下:

WITH test_data AS (
    SELECT '[{
      "actName": "null",
      "applicable": {
        "applicable": [5,4,1]
      },
      "status":1,
      "id":2
      },
      {
      "actName": "null",
      "applicable": {
        "applicable": [3,2]
      },
      "status": 1,
      "id": 1
    }]'::JSONB AS jsonb_value
)
SELECT 
  jsonb_doc->>'id' AS id,
  jsonb_doc->'applicable' #>'{applicable}' AS appl_array_result
FROM
  test_data td,
  jsonb_array_elements(td.jsonb_value) AS jsonb_doc
WHERE (jsonb_doc->'applicable' #>'{applicable}') @> '2'::JSONB;

输出:

 id | appl_array_result 
----+-------------------
 1  | [3, 2]
(1 row)

答案 2 :(得分:0)

使用JSONB的@>,您可以按照文档的结构查询任何元素,例如:

WITH data(d) AS (VALUES
    ('{
        "actName": null,
        "applicable": {
            "applicable": [ 5, 4, 1 ]
        },
        "status": 1,
        "id": 2
    }'::JSONB),
    ('{
        "actName": null,
        "applicable": {
            "applicable": [ 3, 2 ]
        },
        "status": 1,
        "id": 1
    }')
)
SELECT d ->> 'id' AS id
FROM data
WHERE d @> '{"applicable":{"applicable":[1]}}';