postgresql

时间:2015-09-26 17:27:48

标签: php sql postgresql

我使用postgres,我有一个json列,实际上包含2D结构,例如此列中的内容是

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

我想在列"Fourth"的这个json中添加一个新行,所以在更新后这应该像

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

想要获取此列中的总行数,然后将其递增1,然后使用文本Fourth

更新它

任何想法?

1 个答案:

答案 0 :(得分: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)