首页 > 解决方案 > 使用 json_to_record() 向表 PostgresSQL 添加新行

问题描述

我有两列的 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 integer、name VARCHAR、手机 VARCHAR、address TEXT、additional_info TEXT。

所以我的函数应该解析json字段并将每个值放在Table_B的相应列中(假设所有可能的列都存在于Table_B中)。

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

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

标签: pythonjsondatabasepostgresqlpygresql

解决方案


您应该在横向连接中使用该功能。应在函数返回时添加列定义列表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 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)

推荐阅读