如何编写一个 SQL 查询,它使用 table a_json 的 JSON 格式来填充 table b 及其在 postgresql 中的相应值
How to write a SQL query which uses the JSON format of table a_json to populate table b with its respective values in postgresql
我有一个名为 data.json 的文件。
结构是这样的:
{ "PrimKey1": { "layout": "normal", "col1": "PrimKey1",
"__colll2__": "sometext", "col3": 9, "OTHERCOLUMN":"dontneedthis", "col4": ["texxt"] },
... ,
{"PrimKey500": { "layout": "normal", "col1": "PrimKey500",
"col2": "someothertext", "col3": 1, "col4": ["texxtagain"] }}
数据加载到 table a_json 中:
CREATE TABLE a_json (
data json
);
\copy a_json FROM 'mypath/data.json/';
由于 table 不是预期的格式,我创建了一个名为 b.table 的新 table。
CREATE TABLE b (
col1 text PRIMARY KEY,
col2 text,
col3 numeric,
col4 text
);
其中列以我需要的列命名 data.json。
现在,我想将 table a_json 中的所有内容插入 b。
我试过了
INSERT INTO b
SELECT * from a_json json_each(data);
得到了
ERROR: index row requires 1945656 bytes, maximum size is 8191
您可以为此使用 json_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"]
我有一个名为 data.json 的文件。 结构是这样的:
{ "PrimKey1": { "layout": "normal", "col1": "PrimKey1",
"__colll2__": "sometext", "col3": 9, "OTHERCOLUMN":"dontneedthis", "col4": ["texxt"] },
... ,
{"PrimKey500": { "layout": "normal", "col1": "PrimKey500",
"col2": "someothertext", "col3": 1, "col4": ["texxtagain"] }}
数据加载到 table a_json 中:
CREATE TABLE a_json (
data json
);
\copy a_json FROM 'mypath/data.json/';
由于 table 不是预期的格式,我创建了一个名为 b.table 的新 table。
CREATE TABLE b (
col1 text PRIMARY KEY,
col2 text,
col3 numeric,
col4 text
);
其中列以我需要的列命名 data.json。
现在,我想将 table a_json 中的所有内容插入 b。 我试过了
INSERT INTO b
SELECT * from a_json json_each(data);
得到了
ERROR: index row requires 1945656 bytes, maximum size is 8191
您可以为此使用 json_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"]