在列中具有特定值的新行上创建 postgres 触发器

Create a postgres trigger on new row with specific value in column

我有一个 table,replies,我想更新 posts 中的特定行,当 replies 插入了一个外键来自posts.

这是我目前得到的:

-- Inserts a row into public.users
create or replace function public.handle_updated_at() 
returns trigger as $$
begin
  update posts set updated_at = now() where postid = (postid) 
  -- not sure what goes here ^, postid comes from public.replies as a foreign key of posts

  return new;
end;
$$ language plpgsql security definer;

-- Trigger the function every time a user is created
create trigger on_new_reply
  after insert on public.replies
  for each row execute procedure public.handle_updated_at();

我不确定正确的方法是什么,因为我对 SQL 相关的事情没有太多经验,而且我发现 Postgres 文档很难理解。

我的问题仍然存在,我的 trigger/function/both 应该是什么样子才能完成上述建议的这项工作?

你还没有发布你的 table 定义所以我假设 postid 是唯一的(或 PK) posts table 和 [=13= 中的 FK ].正如您的函数目前所处的那样,它会更新 posts table 中的 每一行 。 where 子句中的额外括号对 Postgres 没有任何意义。所以 where postid = (postid)where postid = postid 完全相同。对于 table 中的每一行都是如此,或者与没有 where 子句相同。要仅获取正在更新的 postid 行,请引用 new.postid。所以你的触发函数变成:

-- Inserts a row into public.users
create or replace function public.handle_updated_at() 
returns trigger as $$
begin
  update posts 
     set updated_at = now() 
   where postid = new.postid;
  return new;
end;
$$ language plpgsql security definer;

你的触发器本身没问题。