将值添加到jsonb现有密钥并更新其他postgres

时间:2018-05-29 15:33:07

标签: sql json postgresql

如何向jsonb键添加值? 示例`

{"drivers": "15","updatedat":"someDate"}

之后必须

{"drivers":"15,...,26","updatedat":"nowTime"}

updatedat从节点插入,所以没有问题,我可以选择节点中的派生值,添加新的和更新,还有其他方法使用1个查询而不使用节点吗?

1 个答案:

答案 0 :(得分:0)

如果我理解您的任务正确,您只需要jsonb_set

t=# select jsonb_set('{"drivers": "15","updatedat":"someDate"}'::jsonb, '{updatedate}'::text[],to_jsonb(now()));
                                          jsonb_set
----------------------------------------------------------------------------------------------
 {"drivers": "15", "updatedat": "someDate", "updatedate": "2018-05-29T15:49:41.772188+00:00"}
(1 row)

除非你有旧版本的课程......

更新以更改驱动程序值:

t=# with c(j) as (values('{"drivers": "15","updatedat":"someDate"}'::jsonb))
select jsonb_set(j,'{drivers}'::text[],to_jsonb(j->>'drivers'||',...,26')) from c;
                     jsonb_set
---------------------------------------------------
 {"drivers": "15,...,26", "updatedat": "someDate"}
(1 row)