Postgresql触发器计算总分

时间:2015-07-22 15:10:33

标签: sql postgresql stored-procedures triggers

我正在尝试学习如何在postgresql中创建触发器。我有一张桌子

Thread_user - 表名 thread_id单 用户身份 点

线程 - 表名 thread_id单 total_points

我想更新任何thread_user行以更新线程表中的总点数。我需要基本上从thread_user中选择*,其中thread_id =插入项的thread_id,然后添加点然后更新threads表中的thread_points。我相信这是在触发器中完成的,但也许存储过程会更好。

1 个答案:

答案 0 :(得分:3)

第一步是创建一个计算点总和的函数,并更新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();