使用 Postgres 9.4,我正在寻找一种在查询中合并两个(或更多)json
或 jsonb
列的方法。以下表为例:
id | json1 | json2
----------------------------------------
1 | {'a':'b'} | {'c':'d'}
2 | {'a1':'b2'} | {'f':{'g' : 'h'}}
是否可以让查询返回以下内容:
id | json
----------------------------------------
1 | {'a':'b', 'c':'d'}
2 | {'a1':'b2', 'f':{'g' : 'h'}}
很遗憾,我无法定义 here 中描述的函数.这可以通过“传统”查询实现吗?
最佳答案
在 Postgres 9.5+ 中,您可以像这样合并 JSONB:
select json1 || json2;
或者,如果是 JSON,必要时强制转换为 JSONB:
select json1::jsonb || json2::jsonb;
或者:
select COALESCE(json1::jsonb||json2::jsonb, json1::jsonb, json2::jsonb);
(否则,json1
或 json2
中的任何 null 值都会返回空行)
例如:
select data || '{"foo":"bar"}'::jsonb from photos limit 1;
?column?
----------------------------------------------------------------------
{"foo": "bar", "preview_url": "https://unsplash.it/500/720/123"}
感谢@MattZukowski 在评论中指出这一点。
https://stackoverflow.com/questions/30101603/