我是博士后新手,我有一个关于触发器的问题。假设我们有两张桌子。一个有城市,一个有人。
城市:
人:
当表people中的'processed'值从0更新为1时,我需要一个触发器,用于将表cities中的'processed'值从0更新为1。
例如:John、Ian和Claire来自柏林,当“processed”值为每个值更新为1时,触发器将表cities中柏林的processed值更新为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();