我有两张桌子。表 x 和表 y。表 x 每天都会更新。我希望在表 x 中插入新数据后立即更新表 y。表 y 包含表 x 中每天所有更新的聚合值。
Date为Date类型,其余两列为real类型。
Table_x 可以每天更新,table_y 应自动更新。
Table x
:
Date Sales product
12/12/2017 4000 2
12/12/2017 3000 1
12/12/2017 2000 1
12/12/2017 5000 3
11/12/2017 1000 3
11/12/2017 2000 4
Table y
(如下图所示更新):
Date Sales product
12/12/2017 14000 7
11/12/2017 3000 7
我编写了如下所示的触发器函数,但它更新每个项目而不是聚合值。
CREATE OR REPLACE FUNCTION public.rec_insert_table_y()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO table_y ("Date","Sales","product")
SELECT NEW."Date",(sum(NEW."Sales")),(sum(NEW."product"))
GROUP BY NEW."Date";
RETURN NEW;
触发功能:
CREATE TRIGGER insert_into_table_y
AFTER INSERT
ON public.table_x
FOR EACH ROW
EXECUTE PROCEDURE public.rec_insert_table_y();
您可以编写一个触发器,用于更新聚合值(如果存在)或插入(如果不存在)。
此外,您还必须注意“x”表中的更新和删除:
create function y_x_trg() returns trigger
language plpgsql
as
$body$
declare
row_exists boolean;
begin
if tg_op<>'INSERT' then
update y
set sales = y.sales - old.sales,
product = y.product - old.product
where y.date = old.date
returning true into row_exists;
end if;
if tg_op<>'DELETE' then
update y
set sales = y.sales + new.sales,
product = y.product + new.product
where y.date = new.date
returning true into row_exists;
if row_exists is not true then
insert into y values (new.date, new.sales, new.product);
end if;
return new;
else
return null;
end if;
end;
$body$;
create trigger y_x_trg AFTER INSERT OR UPDATE OR DELETE ON x
FOR EACH ROW EXECUTE PROCEDURE y_x_trg();
您可以在以下位置查看正在运行的示例http://rextester.com/FVR79644 http://rextester.com/FVR79644
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)