Postgres,函数,在插入vladate数组值之前

时间:2018-07-18 14:51:00

标签: sql postgresql

这是我的功能`

create or replace function test.insert(_orderid integer, __partnerids      
integer[], __maginitude double precision[])
returns boolean
language plpgsql
as $$
DECLARE  res boolean;
BEGIN
PERFORM orderid
FROM test.order_partner_magnitude
WHERE orderid = _orderid
FOR UPDATE SKIP LOCKED;

DELETE
FROM test.order_partner_magnitude
WHERE orderid = _orderId;

INSERT INTO test.order_partner_magnitude(orderid, partnerid, magnitude)
SELECT _orderId, unnest(__partnerids),unnest(__maginitude);

res =true ;
RETURN res;
end ;
$$;

某些使用示例SELECT test.insert(1, '{30,10,20}','{46,59,12}');的结果将是

orderid | partnerid | magnitude
      1 |        30 |        46
      1 |        10 |        59
      1 |        20 |        12

现在我需要检查合作伙伴是否繁忙,我可以通过此查询获取繁忙的合作伙伴ID SELECT partnerid from test.order_partner WHERE status = 1;

id为20的示例伙伴在插入结果后必须为`

orderid | partnerid | magnitude
      1 |        30 |        46
      1 |        10 |        59

我想使用函数中的1个插入查询插入所有数据,因此无法从参数循环partnerid,还有其他方法可以执行吗?如果没有方法,我可以更改数据类型,例如[[partnerid, magnitude],[partnerid, magnitude]......]或其他任何类型的女巫都会帮助解决此问题。

1 个答案:

答案 0 :(得分:1)

可以在一个查询中执行,例如EG:

db=# with c(o, p, m) as (values (1, '{30,10,20}'::int[],'{46,59,12}'::int[]))
, op(i, status) as (values(20,1))
, mypart as (select o, unnest(p) pa, unnest(m) me from c)
select mypart.*
from mypart
left outer join op on i = pa
where i is null;
 o | pa | me
---+----+----
 1 | 30 | 46
 1 | 10 | 59
(2 rows)

所以对您来说,像这样:

INSERT INTO test.order_partner_magnitude(orderid, partnerid, magnitude)
with c(o, p, m) as (values (_orderId, __partnerids, __maginitude))
    , mypart as (select o, unnest(p) pa, unnest(m) me from c)
    select mypart.*
    from mypart
    left outer join test.order_partner on partner_id = pa
    where i is null;