我有两个表 accounts
和 projects
:
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/