python - 使用 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 连接我的数据库。
解决方案
您应该在横向连接中使用该功能。应在函数返回时添加列定义列表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)
推荐阅读
- python - TypeError:“模块”对象不可调用 perlin_noise 错误
- python - 使用 Facebook python SDK 下载发票
- javascript - 在 Firefox 中,当窗口最小化或集中在另一个选项卡上时,websockets 会发生什么?
- xml - 从 sql 和 xml 字段 Powershell 获取数据
- flutter - 如何在操作中删除特定的 Row 小部件
- nginx - Nginx 重定向动态页面
- javascript - node.js 向控制器中的特定用户发送通知
- anaconda - 在 conda 依赖项 yml 中,第二个 = 之后是什么。例如 pandas=1.2.4=py38h1abd341_0
- visual-studio-code - VSCode 未检测到来自 node_modules 的导入路径
- javascript - 使用 NextJS API 时出现顶级等待错误