如何编写Postgres触发器插入replies新行时更新对应posts表记录
修正后的完整实现代码
-- 插入回复后更新对应帖子的更新时间 create or replace function public.handle_post_updated_at() returns trigger as $$ begin update posts set updated_at = now() where postid = NEW.postid; -- 取刚插入的回复行关联的帖子ID return new; end; $$ language plpgsql security definer; -- 每次向replies表插入新行时触发函数 create trigger on_new_reply after insert on public.replies for each row execute procedure public.handle_post_updated_at();
主要修改说明
- 修正了原代码中不匹配的注释内容,和实际功能对应
UPDATE语句的查询条件使用触发器内置变量NEW获取刚插入的replies行数据,从中取出关联的postid匹配posts表的对应行- 重命名了函数名,更贴合实际功能避免歧义
补充说明
如果你的replies表中关联posts的外键字段名不是postid,把上面代码里的NEW.postid替换成你实际的外键字段名即可。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

