Python 使用json_to_record()将新行添加到表PostgresSQL
我有两列的表A:Python 使用json_to_record()将新行添加到表PostgresSQL,python,json,database,postgresql,pygresql,Python,Json,Database,Postgresql,Pygresql,我有两列的表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"}'); 我想写一个函数,从表a中取出一行,然后在表B中插入新行。表B有以下列:id integer、name VARCHAR、mobile VARCHAR、address
create table table_a(id int, data json);
一行可以是:
insert into table_a values
(1, '{"name": "kate", "cellphone": "000-000-0000", "address": "some text here"}');
我想写一个函数,从表a中取出一行,然后在表B中插入新行。表B有以下列:id integer、name VARCHAR、mobile VARCHAR、address TEXT、additional_info TEXT
因此,我的函数应该解析json字段,并将每个值放在表_B的相应列中(假设表_B中存在所有可能的列)
看起来我可以使用json_to_记录(json),但如何将返回值插入表_B
我正在使用PyGreSQL连接我的数据库。您应该在横向连接中使用该函数。当函数返回
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)