使用json_to_record()将新行添加到表PostgresSQL

时间:2018-12-14 22:49:57

标签: python json database postgresql pygresql

我有两列的table_A:

create table table_a(id int, data json);

一行可能是:

insert into table_a values
(1, '{"name": "kate", "cellphone": "000-000-0000", "address": "some text here"}');

我想编写一个函数,该函数将从table_A中获取一行并将新行插入table_B中。 Table_B具有以下列:ID整数,名称VARCHAR,手机VARCHAR,地址TEXT,Additional_info TEXT。

因此,我的函数应解析json字段,并将每个值放入Table_B的对应列中(假设Table_B中存在所有可能的列)。

看起来我可以使用json_to_record(json),但是如何将返回的值插入到Table_B中呢?

我正在使用PyGreSQL连接数据库。

1 个答案:

答案 0 :(得分:1)

您应该在横向连接中使用该功能。当函数返回record时,应添加列定义列表。

select id, r.*
from table_a
cross join lateral 
    json_to_record(data) 
    as r(name varchar, cellphone varchar, address text, additional_info text)

 id | name |  cellphone   |    address     | additional_info 
----+------+--------------+----------------+-----------------
  1 | kate | 000-000-0000 | some text here | 
(1 row) 

insert语句可能看起来像这样:

insert into table_b
select id, r.*
from table_a
cross join lateral 
    json_to_record(data) 
    as r(name varchar, cellphone varchar, address text, additional_info text)