postgresql - postgres 在触发器中插入之前更新新变量

标签 postgresql triggers

我有两个表 accountsprojects:

create table accounts (
  id          bigserial primary key,
  slug        text unique
);


create table projects (
  id          bigserial primary key,
  account_id  bigint not null references accounts (id),
  name        text
);

我希望能够通过仅指定 account.slug(而不是 account.id)向 projects 中插入一个新行。我想要实现的是:

INSERT into projects (account_slug, name) values ('account_slug', 'project_name');

我考虑过使用触发器(不幸的是它不起作用):

create or replace function trigger_projects_insert() returns trigger as $$
begin
  if TG_OP = 'INSERT' AND NEW.account_slug then

    select id as account_id
      from accounts as account
      where account.slug = NEW.account_slug;

    NEW.account_id = account_id;

    -- we should also remove NEW.account_slug but don't know how

  end if;
  return NEW;
end;
$$ LANGUAGE plpgsql;

create trigger trigger_projects_insert before insert on projects
  for each row execute procedure trigger_projects_insert();

实现我想要做的事情的最佳方式是什么?

触发器是个好主意吗? 还有其他解决办法吗?

最佳答案

WITH newacc AS (
   INSERT INTO accounts (slug)
      VALUES ('account_slug')
      RETURNING id
)
INSERT INTO projects (account_id, name)
   SELECT id, 'project_name'
      FROM newacct;

如果您在可以使用的 SQL 方面受到限制,另一个想法可能是在两个表上定义一个 View ,并在执行两个 INSERT 的 View 上创建一个 INSTEAD OF INSERT 触发器 在基础表上。然后像您问题中的那样的 INSERT 语句将起作用。

关于postgresql - postgres 在触发器中插入之前更新新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42690148/

相关文章:

ruby - 如何从 DataMapper::Collection 获取原始 SQL?

python - 如何在 PostgreSQL 数据库中存储 NumPy 数组?

triggers - 在 db2 中启用和禁用触发器

mysql - 创建触发器以在 MySQL 中的另一个表中插入新行时更新表

sqlite - 如何处理 SQLite : disable triggers? 的缺失功能

bash - 在 BASH 中使用与 PostgreSQL 的开放数据库连接?

postgresql - 使用先前 DO 子句中的变量

sql - 如果条件匹配,则计算行中的列

MySQL 复制 - 触发器不会复制到从属

oracle - 在 Oracle 中执行触发器以将旧值复制到镜像表