我正在尝试学习如何在 postgresql 中创建触发器。我有一张桌子
Thread_user - 表名
thread_id user_id points
线程 - 表名称
thread_id total_points
我想在更新任何
thread_user
行时更新线程表中的总点数。我基本上需要 select * from thread_user where thread_id = <thread_id of inserted item>
,然后添加点,然后更新线程表中的 thread_points
。我相信这是在触发器中完成的,但也许存储过程会更好。
第一步是创建一个计算点数总和并更新
calculated_points
表中的行的函数。
此后,您必须创建一个触发器,在
user_points
表中插入行时调用该触发器。
DROP TABLE IF EXISTS user_points CASCADE;
CREATE TABLE user_points (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
points INT NOT NULL
);
DROP TABLE IF EXISTS calculated_points CASCADE;
CREATE TABLE calculated_points (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL UNIQUE,
points INT NOT NULL
);
INSERT INTO calculated_points (user_id, points)
VALUES
(1, 0),
(2, 0);
CREATE OR REPLACE FUNCTION calculate_total_points()
RETURNS trigger AS $calculate_total_points$
BEGIN
UPDATE calculated_points
SET points = (SELECT SUM(points)
FROM user_points
WHERE user_id = NEW.user_id)
WHERE user_id = NEW.user_id;
RETURN NEW;
END;
$calculate_total_points$ LANGUAGE plpgsql;
CREATE TRIGGER points_added
AFTER INSERT
ON user_points
FOR EACH ROW
EXECUTE PROCEDURE calculate_total_points();