2016-01-12 69 views
0
{ 
    actName: null, 
    applicable: { 
     applicable: [ 5, 4, 1 ] 
    }, 
    status: 1, 
    id: 2 
} 
{ 
    actName: null, 
    applicable: { 
     applicable: [ 3, 2 ] 
    }, 
    status: 1, 
    id: 1 
} 

這有可能在數組找到價值,就像如果我搜索整數值2applicable陣列返回一行ID爲1如何返回行,如果值找到數組中的Postgres

+0

您可以使用數組「包含」操作是這樣的:'可應用@> array [2]' – Hambone

+0

你有無效的json結構 –

+0

@Dmitry你不應該改變問題代碼或數據。這是問題的一部分。 –

回答

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 
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) 
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]}}'; 
相關問題