我正在尝试学习如何在 postgresql 中创建触发器。我有一张 table
Thread_user - 表名 thread_id 用户身份 积分
线程-表名 thread_id 总分
我想更新任何 thread_user 行以更新线程表中的总点数。我需要基本上选择 * from thread_user where thread_id = thread_id of inserted item 然后添加点然后更新 threads 表中的 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();
关于sql - Postgresql触发器计算总分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567135/