我有三个这样的表:
订单(产品ID(外键),人员ID(外键),订单数)
产品(product_id(主键),价格)
零售商(personnel_id(主键),佣金)
我正在尝试创建一个触发器,该触发器会在零售商的帮助下下达的每笔订单都增加零售商的佣金。
这是我的触发器代码。但似乎有一个错误,它会使用每个插入内容来更新Retailers表中的每条记录(或其他一些会在Retailers表中导致错误结果的错误)
CREATE OR REPLACE FUNCTION update_commission() RETURNS TRIGGER AS $table$
BEGIN
update "Retailers" rt
set commission = commission + (res.order_count * res.price * 0.005)
from
(select r.personnel_id, o.order_count, p.price from
"Orders" o left join "Retailers" r
on r.personnel_id = o.personnel_id
left join "Products" p
on o.product_id = p.product_id) as res
where NEW.personnel_id = res.personnel_id;
return NEW;
END;
$table$ LANGUAGE plpgsql;
CREATE TRIGGER new_order
AFTER INSERT
ON "Orders"
FOR EACH ROW
EXECUTE PROCEDURE update_commission();