2016-06-22 89 views
1

我有表有這樣的數據:如何篩選JSONB列表

id  | 1 
accounts | [{"id": "100", "properties": [{"id": "PR-001", "name": "name1"}, {"id": "PR-002", "name": "name2"}]}] 
property | "PR-001" 

accounts是jsonb場。

我需要獲取所有property.name其中accounts.property.id等於與SELECT屬性。

我使用的是Postgres 9.5

+0

這一個工程:)是好? 'SELECT DISTINCT x.properties - >> '名稱' FROM MY_TABLE噸,( SELECT json_array_elements(json_array_elements(帳戶:: JSON) - > '屬性')AS屬性 FROM MY_TABLE )x其中x.properties - >> 'id'= t.property;' – HoTicE

回答

1

您可以使用左外連接:

WITH tbl (id,accounts,property) AS (
    SELECT 1, '{"id": "100", "properties": [{"id": "PR-001", "name": "name1"}, {"id": "PR-002", "name": "name2"}]}'::jsonb, 'PR-001'::text 
) 
SELECT t.id, acc->>'name' 
FROM tbl t 
LEFT JOIN LATERAL jsonb_array_elements(t.accounts->'properties') acc ON (acc->>'id' = t.property)