2014-09-22 33 views
5

在Postgres 9.3數據庫中,我有一個表,其中一列包含JSON,如下面示例中所示的測試表中所示。Postgres:將JSON列擴展爲行

test=# create table things (id serial PRIMARY KEY, details json, other_field text); 
CREATE TABLE 
test=# \d things 
          Table "public.things" 
    Column | Type |      Modifiers 
-------------+---------+----------------------------------------------------- 
id   | integer | not null default nextval('things_id_seq'::regclass) 
details  | json | 
other_field | text | 
Indexes: 
    "things_pkey" PRIMARY KEY, btree (id) 

test=# insert into things (details, other_field) 
     values ('[{"json1": 123, "json2": 456},{"json1": 124, "json2": 457}]', 'nonsense'); 
INSERT 0 1 
test=# insert into things (details, other_field) 
     values ('[{"json1": 234, "json2": 567}]', 'piffle'); 
INSERT 0 1 
test=# select * from things; 
id |       details       | other_field 
----+-------------------------------------------------------------+------------- 
    1 | [{"json1": 123, "json2": 456},{"json1": 124, "json2": 457}] | nonsense 
    2 | [{"json1": 234, "json2": 567}]        | piffle 
(2 rows) 

JSON始終是一個包含可變數量散列的數組。每個散列總是具有相同的一組鍵。我正在嘗試編寫一個查詢,它將爲JSON數組中的每個條目返回一行,併爲每個散列鍵和來自things表的id添加列。我希望輸出如下:

thing_id | json1 | json2 
----------+-------+------- 
     1 | 123 | 456 
     1 | 124 | 457 
     2 | 234 | 567 

即兩行條目與JSON數組中的兩個項目。是否有可能讓Postgres做到這一點? json_populate_recordset感覺是答案的重要組成部分,但我無法一次處理多行。

回答

6
select id, 
    (details ->> 'json1')::int as json1, 
    (details ->> 'json2')::int as json2 
from (
    select id, json_array_elements(details) as details 
    from things 
) s 
; 
id | json1 | json2 
----+-------+------- 
    1 | 123 | 456 
    1 | 124 | 457 
    2 | 234 | 567