【问题标题】:PostgreSQL insert triggers and many-to-many tablesPostgreSQL 插入触发器和多对多表
【发布时间】:2021-10-01 17:12:04
【问题描述】:

我在 postgres 数据库 articlesusers 中有两个表。这两个表通过多对多关系连接,因此还有第三个表称为articles_users,其中包含与articlesusers 的外键关系。

我想做的是创建一个触发器,该触发器在将新条目插入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


【解决方案1】:

您的触发器已经为插入文章的每一行执行了函数,您不需要为用户循环,您可以在一个insert中插入多行:

CREATE OR REPLACE FUNCTION connect_articles_to_users()
 RETURNS trigger AS
$$
BEGIN
 INSERT INTO articles_users (article_id, user_id)
  SELECT NEW.id, id FROM users
 ;
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';

【讨论】:

  • 这里有一个例子newbedev.com/…
  • 哎呀!这行得通。太感谢了。这让我免于很多痛苦。
【解决方案2】:

如果 articles_users 表有列 article_iduser_id 为每个用户插入一行

    insert into articles_users (article_id, user_id) 
    select new.id, users.id
    from users;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    相关资源
    最近更新 更多