如何在postgresql中编写一个sql查询,它使用表a的json格式来填充表b的值

ubby3x7f  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(286)

我有一个名为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"] }}

数据被加载到表a中,其中包含:

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的所有内容插入到b中。我试过了

INSERT INTO b
SELECT * from a_json json_each(data);

得到了
错误:索引行需要1945656字节,最大大小为8191

sqougxex

sqougxex1#

你可以用 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)

db小提琴演示:

col1       | col2          | col3 | col4          
:--------- | :------------ | ---: | :-------------
PrimKey1   | sometext      |    9 | ["texxt"]     
PrimKey500 | someothertext |    1 | ["texxtagain"]

相关问题