我是postgres新手,我有一个关于触发器的问题。可以说我们有2张桌子。一个与城市,一个与人。
城市:
大家:
我需要一个触发器,当表格中的“已处理”值从该城市的所有人更新为0时,表格城市中的“已处理”值从0更新为1.
例如:John,Ian和Claire来自柏林,每当“处理”值更新为1时,触发器会将表格城市中柏林的处理值更新为1。
最好的方法是什么?
答案 0 :(得分:1)
尝试此查询:
with c as (
select city_id
from people
where name = NEW.name
)
, a as (
select avg(processed)
from people
join c on c.city_id = people.city_id
)
update cities u
set processed = 1
from a
where u.id = a.city_id
and avg = 1
alias c获取城市ID,然后为人们的sict id处理聚合,并且只有在处理完所有名称时才更新更新。
答案 1 :(得分:1)
这将有效:
CREATE OR REPLACE FUNCTION mytrigger() RETURNS TRIGGER AS $mytrigger$
BEGIN
IF (SELECT EXISTS (SELECT 1 FROM PEOPLE WHERE city_id = NEW.city_id AND processed = '0')) THEN
UPDATE CITIES SET processed = '0' WHERE id = NEW.city_id;
RETURN NEW;
ELSE
UPDATE CITIES SET processed = '1' WHERE id = NEW.city_id;
RETURN NEW;
END IF;
END;
$mytrigger$ LANGUAGE plpgsql;
CREATE TRIGGER mytrigger
AFTER UPDATE ON PEOPLE
FOR EACH ROW EXECUTE PROCEDURE mytrigger();