我想在posgres中优化批量插入。 为此,我必须找到json数据的最新值并在另一个json数据中使用它。 现在,我的查询看起来像这样:
INSERT INTO audits ("audited_changes")
VALUES
('update', '{"step_id":[(SELECT ((audited_changes -> `step_id`)::json->>1) FROM audits WHERE auditable_id = 123 order by id desc limit 1)::int,3]}')
但是postgres不允许我在json中执行子查询。 我能怎么做 ?
答案 0 :(得分:0)
我建议你尝试:
INSERT INTO audits ("audited_changes")
SELECT 'update'
, '{"step_id":['||((audited_changes -> 'step_id')::json->>1)::int||',3]}'
FROM audits
WHERE auditable_id = 123
order by id desc
limit 1
答案 1 :(得分:0)
我发现使其工作的唯一方法是使用jsonjson_build_object()和json_build_array()函数
我的查询现在看起来像:
INSERT INTO audits ("action", "audited_changes", "auditable_id", "auditable_type", "created_at", "version", "request_uuid")
VALUES ('update', json_build_object('zone',json_build_array((SELECT ((audited_changes -> 'zone')::json->>1) FROM audits WHERE auditable_id = 1209103 order by id desc limit 1),'qwertyuiop')), 1209103, 'Followup', '2017-11-09 17:03:40 +0400', (SELECT max(version) FROM audits where auditable_id= 1209103)+1, 'cbd34343-1dc1-42b0-ade3-788dfb2c1172')