Postgresql 从复合类型数组和一列附加列中多插入

问题描述

我有什么:

CREATE TYPE Item AS (
    a bigint,b bigint
);

CREATE TABLE items (
    id bigint NOT NULL,a bigint NOT NULL,b bigint NOT NULL
);

CREATE OR REPLACE FUNCTION items_insert(
        _id bigint,_items Item[]
) RETURNS void AS
...

如何通过一个多插入查询将多 行插入到 _items 中具有相同 _id 的表项中?

我使用的是 Postgresql-9.2

解决方法

我认为您的意思是“插入多个”而不是列。

假设这是正确的,我认为您正在寻找这样的函数:

create or replace function items_insert(_id bigint,_items item[]) 
  returns void 
as
$$
  insert into items (id,a,b)
  select _id,it.*
  from unnest(_items) as it(a,b);
$$
language sql;

Online example