2015-09-26 48 views
0

使用Postgres的IM,我有一個JSON列,這實際上是包含2D結構,例如在此列中的內容是PostgreSQL中JSON列的行數

[ 
    {"in_id":1,"item":"Firsty"}, 
    {"in_id":2,"item":"Second"}, 
    {"in_id":3,"item":"Third"} 
] 

我想添加一個新的排進這個JSON列"Fourth",以便更新後,這應該是像

[ 
    {"in_id":1,"item":"Firsty"}, 
    {"in_id":2,"item":"Second"}, 
    {"in_id":3,"item":"Third"}, 
    {"in_id":4,"item":"Fourth"} 
] 

想獲得總排在此列,然後加1,然後用文Fourth

更新

有什麼想法?

+0

的Postgres目前不具備這樣的功能開箱。您可以使用具有JavaScript的PLV8語言。你可以使用第二個表作爲詳細表嗎? – Skoffer

回答

0

設置:

create table json_test (id int primary key, val json); 
insert into json_test values 
(1, 
'[ {"in_id":1,"item":"Firsty"}, 
    {"in_id":2,"item":"Second"}, 
    {"in_id":3,"item":"Third"}]'); 

使用json_array_elements()json_agg()

with base_query as (
    select json_array_elements(val) elements 
    from json_test 
    where id = 1 
    ), 
union_query as (
    select elements::text 
    from base_query 
    union 
    select '{"in_id":' || count(*)+ 1 || ',"item":"Fourth"}' 
    from base_query 
    ) 
update json_test 
set val = 
    (select json_agg(elements::json) 
    from union_query) 
where id = 1; 

結果:

select * from json_test; 

id |               val              
----+--------------------------------------------------------------------------------------------------------------------- 
1 | [{"in_id":1,"item":"Firsty"}, {"in_id":2,"item":"Second"}, {"in_id":3,"item":"Third"}, {"in_id":4,"item":"Fourth"}] 
(1 row)