2017-08-13 24 views
2

これらの列とのPostgres 9.6テーブルがある:抽出および別のテーブルへのPostgres JSON列データを展開

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内に同一の構造を共有します。

質問: 私は、各トップレベルのJSONのキーの列で空の新しい一時テーブルにclassに一致するすべてのjsonbdataの行を抽出し、そして私のクエリを構築するいくつかの助けを必要としたいと思います。

私は今でよ

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 table targettable_class_1 as 
-- create temp table targettable_class_1 as 
-- create view targettable_class_1 as 
select * 
from targettable 
where class = 1; 

をフラットビューを作成するための関数を使用します。

答えて

2

あなたは指定されたクラス用のテーブルを作成しますin this answer.

を説明create_jsonb_flat_view()機能(または一時テーブルまたはビュー)を使用することができます。

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)  
+0

これは有望です。その答えの関数を解析して報告します。ありがとう! – sheepgobeep

+0

機能は期待通りに機能します!キーで渡された引用符が一重引用符であれば、関数はエラーをスローするようです。考えられる例:{"Fruit's name": "Mango"}は構文エラーを生成します。 – sheepgobeep

+1

@sheepgobeep - 私は関数を修正しました、あなたはそれを確認することができます。先端に感謝します。 – klin

関連する問題