我想在game_catalog
表上创建一个触发器,这样每次用户从他的收藏中添加或删除游戏时,总游戏数就会更新。由于游戏集合存储为文本数组,我决定使用array_length函数来计算游戏数量。
game_catalog
id - BIGSERIAL primary key
user_id - INTEGER
game_list - text []
game_count - INTEGER
我试图创建一个触发器,以便在插入或删除后重新计算game_list
列的长度,但它不起作用。这就是我现在所拥有的:
CREATE OR REPLACE FUNCTION count_games()
RETURNS TRIGGER AS $$
BEGIN
UPDATE game_catalog
SET game_count = (SELECT array_length(game_list, 1) from game_catalog)
WHERE user_id = NEW.user_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER count_games
AFTER INSERT OR DELETE ON game_catalog FOR EACH ROW
EXECUTE PROCEDURE count_games();
答案 0 :(得分:1)
所以,有几件事:
也就是说,您可以不同地定义触发器以使其工作:
-- only watch for insert/updates on the game_list column to avoid infinite loop
-- delete doesn't matter here
CREATE TRIGGER count_games
BEFORE INSERT OR UPDATE OF game_list
ON game_catalog
FOR EACH ROW
EXECUTE PROCEDURE count_games();
虽然视图会更好:
CREATE OR REPLACE VIEW game_catalog_count AS
SELECT id, user_id, game_list, array_length(game_list,1) as game_count
FROM game_catalog;
你的触发器功能可以使用一点改进(除非你计划引用其他行......但是你的触发器功能设计中还有其他问题):
CREATE OR REPLACE FUNCTION count_games()
RETURNS TRIGGER AS $$
BEGIN
NEW.game_count := array_length(NEW.game_list, 1);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
希望有帮助!