[英]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.