Postgresql - 如何在使用特定数据更新一个表后更新另一个表

时间:2015-12-11 08:53:09

标签: database postgresql

我有两张桌子,

CREATE TABLE B(
offer_id serial primary key,
number_of_placement int,
constraint num_of_placement_chk check (number_of_placement >0)
);

create table a (
id serial,
offer_id int references b(offer_id),//refer to table b offer_id
status varchar(20) default 'PENDING');

和我的功能和触发器,

Create or replace function update_no_offer_placement_func() 
returns trigger as $body$
begin
    if(new.status == 'ACCEPTED') then // if the status is update with 'ACCEPTED' value
        update b set number_of_placement = number_of_placement -1; //reduce the number of placement by 1
    end if;
end;
$body$ language plpgsql;

CREATE TRIGGER update_no_offer_placement_trig //after update table a
     AFTER update ON a
     FOR EACH ROW
     EXECUTE PROCEDURE update_no_offer_placement_func();

我想更新表b的位置数,因此如果只更新a中的值为'ACCEPTED',它会将其数量减少1。我该怎么做? 我试过但错了。

1 个答案:

答案 0 :(得分:1)

使用此:

CREATE OR REPLACE FUNCTION update_no_offer_placement_func()
RETURNS trigger AS
$BODY$
BEGIN
UPDATE B SET number_of_placement = number_of_placement -1 FROM a WHERE B.offer_id = a.offer_id AND a.status = 'ACCEPTED';
RETURN NULL;  -- AFTER trigger can return NULL
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

CREATE TRIGGER update_no_offer_placement_trig 
AFTER update ON a
FOR EACH ROW
EXECUTE PROCEDURE update_no_offer_placement_func();