Re: how to implement add using upsert and trigger?

From: Pavel Luzanov <p(dot)luzanov(at)postgrespro(dot)ru>
To: "yin(dot)zhb(at)163(dot)com" <yin(dot)zhb(at)163(dot)com>, pgsql-general <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: how to implement add using upsert and trigger?
Date: 2022-11-28 13:26:49
Message-ID: 02375b28-3e55-f873-5a93-de7b965206f5@postgrespro.ru
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi, I think you need:

    insert into stat_result(itemid,value,cnt) values(new.itemid,
new.value, 1)
    on conflict(itemid) do update
    set value = stat_result.value + new.value, cnt = stat_result.cnt +1;

excluded.value and new.value is the same value from inserted record, but
your need a current value from stat_result.

On 28.11.2022 15:37, yin(dot)zhb(at)163(dot)com wrote:
> Hi, all:
>   when I using upsert and trigger to update other table automatically:
> create table stat_detail(itemid bigint not null, value bigint, captime
> bigint);
> create table stat_result(itemid bigint primary key, value bigint, cnt
> bigint);
> create or replace function inertfunc() returns trigger as $$
> begin
> insert into stat_result(itemid,value,cnt) values(new.itemid, new.value, 1)
> on conflict(itemid) do update
> set value = excluded.value + new.value, cnt = excluded.cnt +1 where
> excluded.itemid = new.itemid;
> return new;
> end;
> $$
> language plpgsql;
> create trigger tri_insert after insert on stat_detail for each row
> execute function inertfunc();
> postgres=# insert into stat_detail values(100,1,1);
> INSERT 0 1
> postgres=# select * from stat_result ;
>  itemid | value | cnt
> --------+-------+-----
> 100 | 1 | 1
> (1 row)
> postgres=# insert into stat_detail values(100,1,1);
> INSERT 0 1
> postgres=# select * from stat_result ;
>  itemid | value | cnt
> --------+-------+-----
> 100 | 2 | 2
> (1 row)
> postgres=# insert into stat_detail values(100,1,1);
> INSERT 0 1
> postgres=# select * from stat_result ;
>  itemid | value | cnt
> --------+-------+-----
> 100 | 2 | 2
> (1 row)
>
> But  I want it is "100 3 3". So how I can do?
>
> ------------------------------------------------------------------------
> yin(dot)zhb(at)163(dot)com

--
Pavel Luzanov
Postgres Professional:https://postgrespro.com
The Russian Postgres Company

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Arlo Louis O'Keeffe 2022-11-28 13:29:30 delete statement returning too many results
Previous Message Anna B. 2022-11-28 13:09:08 Re[2]: Index-only scan not working when IN clause has 2 or more values