如何编写一个SQL查询,该查询使用表a的JSON格式,用postgresql中的相应值填充表b
我有一个名为data.json的文件。 结构如下:如何编写一个SQL查询,该查询使用表a的JSON格式,用postgresql中的相应值填充表b,sql,json,postgresql,sql-insert,psql,Sql,Json,Postgresql,Sql Insert,Psql,我有一个名为data.json的文件。 结构如下: { "PrimKey1": { "layout": "normal", "col1": "PrimKey1", "__colll2__": "sometext", "col3": 9, "OTHERCOLUMN":"dontneedthis", "col4": ["texxt"] }, ... , {"PrimKey500": { "layout": "normal", "col1": "Prim
{ "PrimKey1": { "layout": "normal", "col1": "PrimKey1",
"__colll2__": "sometext", "col3": 9, "OTHERCOLUMN":"dontneedthis", "col4": ["texxt"] },
... ,
{"PrimKey500": { "layout": "normal", "col1": "PrimKey500",
"col2": "someothertext", "col3": 1, "col4": ["texxtagain"] }}
数据加载到表a_json中,其中包含:
CREATE TABLE a_json (
data json
);
\copy a_json FROM 'mypath/data.json/';
由于该表不是预期的格式,因此我创建了一个名为b的新表
CREATE TABLE b (
col1 text PRIMARY KEY,
col2 text,
col3 numeric,
col4 text
);
其中,列以我需要的data.json中的列命名
现在,我想将表a_json中的所有内容插入到b中。
我试过了
得到
错误:索引行需要1945656字节,最大大小为8191
您只需使用
json\u each()
和json访问器即可:
insert into b(col1, col2, col3, col4)
select j.v ->> 'col1', j.v ->> 'col2', (j.v ->> 'col3')::numeric, j.v ->> 'col4'
from a_json a
cross join lateral json_each(a.data) j(k, v)
:
col1 | col2 | col3 | col4
:--------- | :------------ | ---: | :-------------
PrimKey1 | sometext | 9 | ["texxt"]
PrimKey500 | someothertext | 1 | ["texxtagain"]
col1 | col2 | col3 | col4
:--------- | :------------ | ---: | :-------------
PrimKey1 | sometext | 9 |[“texxt”]
PrimKey500 | someothertext | 1 |[“texxtreach”]
col1 | col2 | col3 | col4
:--------- | :------------ | ---: | :-------------
PrimKey1 | sometext | 9 | ["texxt"]
PrimKey500 | someothertext | 1 | ["texxtagain"]