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
内共享相同的结构。
问题:
我想将与jsonbdata
匹配的所有class
行提取到一个空的新临时表中,其中包含每个顶级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对象中的键添加表列。
答案 0 :(得分:2)
您可以使用in this answer.
所述的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)