【发布时间】:2021-10-01 17:12:04
【问题描述】:
我在 postgres 数据库 articles 和 users 中有两个表。这两个表通过多对多关系连接,因此还有第三个表称为articles_users,其中包含与articles 和users 的外键关系。
我想做的是创建一个触发器,该触发器在将新条目插入articles 表时运行,并通过articles_users 表将该文章连接到我的数据库中的每个用户。这是否可以通过触发器实现,如果可以,我应该如何编写?
我对触发器的工作原理有一个粗略的了解,并且有一些看起来像这样的伪sql:
create function public.connect_articles_to_users()
returns trigger as $$
begin
-- Here's some pseudocode to describe what I'd like to happen
-- Not sure if temprow is the right structure here
for temprow in
select * from users
loop
insert into articles_users (id, users.id) values (new.id, users.id)
end loop
return new
end;
$$ language plpgsql security definer;
-- trigger the function every time a and article is created
create trigger on_article_created
after insert on articles
for each row execute procedure public.connect_articles_to_users();
【问题讨论】:
-
您的问题提出了两个明显的问题: 1. 添加用户时会发生什么,他们是否也与所有文章建立了关系? 2.如果所有文章都与所有用户相关,那么交集表articles_users)的意义何在?
标签: sql postgresql