繁体   English   中英

将Postgres JSON列数据提取并展开到单独的表中

[英]Extract and expand Postgres JSON column data into separate table

Postgres 9.6表格包含以下列:

targettable
------------------------------------------------------------------

id | name | jsonbdata                                      | class
------------------------------------------------------------------
1  | A    | {"a":"1","b":"2","c":[{"aa":"1"},{"bb":"2"}]}  | 1
2  | B    | {"a":"2","b":NULL,"c":[{"aa":"3"},{"bb":"2"}]} | 1
3  | C    | {"z":"1","y":"2"}                              | 2

jsonbdata包含具有不同结构的JSON对象,但在同一个class共享相同的结构。

问题:我想将与class匹配的所有jsonbdata行提取到一个空的新临时表中,每个顶级JSON键都有列,并且需要一些帮助构造我的查询。


我现在在哪里:

create temp table testtable (id serial primary key);

with testrow as (select * from targettable where class = 1 limit 1)
select * from jsonb_populate_record(null::testtable, (select to_jsonb(jsonbdata) from testrow));

我认为如果testtable列名与JSON键匹配,这可能会有效,但我不确定如何根据JSON对象的键添加表列。

您可以使用此答案中描述的create_jsonb_flat_view()函数

为给定的类创建表(或临时表或视图):

create table targettable_class_1 as
-- create temp table targettable_class_1 as
-- create view targettable_class_1 as
select *
from targettable
where class = 1;

并使用该函数创建一个平面视图:

select create_jsonb_flat_view('targettable_class_1', 'id, name', 'jsonbdata');

select *
from targettable_class_1_view;

 id | name | a | b |             c              
----+------+---+---+----------------------------
  1 | A    | 1 | 2 | [{"aa": "1"}, {"bb": "2"}]
  2 | B    | 2 |   | [{"aa": "3"}, {"bb": "2"}]
(2 rows)    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM