我正在創建一個過程來解析輸入json數據並存儲在表中。該功能看起來像:Postgresql插入選擇多行
create or replace function test_func(d json)
returns void as $$
begin
with n as (
insert into t1 (name) values (d::json -> 'name') returning id
), c as (
insert into t2 (cars) values json_array_elements_text(d::json -> 'cars') returning id
)
insert into t3 (id, name_id, cars_id, brand)
select 1, n.id, c.id, json_array_elements_text(d::json -> 'brands') from n, c;
end;
$$ language plpgsql;
CREATE TABLE t1
(
"id" SERIAL PRIMARY KEY,
"name" text NOT NULL
)
CREATE TABLE t2
(
"id" SERIAL PRIMARY KEY,
"cars" text NOT NULL,
"car_type" int
)
CREATE TABLE t3
(
"id" int,
"name_id" int REFERENCES t1(id),
"cars_id" int REFERENCES t2(id),
"brand" text
)
數據輸入名稱爲文本,汽車和品牌是數組,都包裹在一個JSON中。 所以最後一個插入有混合值類型,如果人有兩輛車,我有4行插入t3因爲c.id和json_array_elements_text(d :: json - >'品牌')都有兩個數據集,2x2 = 4 ,如何將插入的值映射到一個?所以第一個c.id應該映射到第一個品牌。
你可以添加你的JSON的一個例子,實際結果和預期的結果?並可能描述你的表格。 – cachique
當然,t1存儲id和name:text,t2有id和cars:text(每輛車都有自己的行),t3基本上鍊接t1和t2,添加品牌信息,t3:id:int,name_id(fk到t1), cars_id(fk到t2)和品牌:文本。 json看起來像{姓名:john,汽車:[「bmw X5 xdrive」,「volvo v90 rdesign」]},品牌:[「bmw」,「volvo」]}。預計t3將一個car_id映射到與json數組中相同索引的單品牌。這個功能在t3中插入4行,每輛車出現兩次不同品牌 – Wizer