【问题标题】:Create a postgres trigger on new row with specific value in column在列中具有特定值的新行上创建一个 postgres 触发器
【发布时间】:2021-11-24 11:08:29
【问题描述】:

我有一个表replies,当replies 插入一个带有来自posts 的外键的新行时,我想更新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 文档很难理解。

我的问题仍然存在,我的触发器/函数/两者应该是什么样子才能完成上述工作?

【问题讨论】:

    标签: sql postgresql triggers plpgsql


    【解决方案1】:

    您尚未发布表定义,因此我将假设 postid 是唯一的(或 PK)posts 表和 replies 中的 FK。正如您的函数当前所支持的那样,它会更新posts 表中的每一行。 where 子句中的额外括号对 Postgres 没有任何意义。所以where postid = (postid)where postid = postid 完全相同。这对于表中的每一行都是正确的,或者与无 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;
    

    你的触发器本身没问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2022-07-29
      • 2021-08-07
      • 2022-12-17
      • 2020-08-13
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多