且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用索引将多个数组的值插入表中

更新时间:2021-09-04 08:28:46

您使用t2为两个不同的集合混叠-尝试:

you used t2 for aliasing two different sets - try:

create or replace function test_func(d json)
returns void as $$
  begin
with j as (select d)
, a as (
  select car,brand,car_type, t1.id oid 
  from j
  join json_array_elements_text(j.d->'cars') with ordinality t1(car,id) on true
  join json_array_elements_text(j.d->'brands') with ordinality t2(brand,id) 
on t1.id = t2.id
  join json_array_elements_text(j.d->'car_type') with ordinality car_t(car_type,id) 
on t1.id = car_t.id 
)
, n as (
 insert into t1 (name) values (d::json -> 'name') returning id
), c as (
  insert into t2 (cars,car_type) select car,car_type::int from a order by oid returning id -- needs to insert two columns here from two arrays
)
, ag as (
  select array_agg(c.id) cid from c
)
insert into t3 (id, name_id, cars_id, brand)
  select 1, n.id,cid[oid], brand
  from a 
  join n on true
  join ag on true
;
end;
$$ language plpgsql;

结果:

t=# select * from t2;
 id |       cars        | car_type
----+-------------------+----------
  1 | bmw X5 xdrive     |        1
  2 | volvo v90 rdesign |        1
(2 rows)