You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:45:03