【问题标题】:PostgreSQL - Insert where not exists in another table / Reverse Foreign Key?PostgreSQL - 在另一个表中不存在的地方插入/反向外键?
【发布时间】:2020-10-30 22:24:23
【问题描述】:

我在 PostgreSQL 数据库中有两个表:Records 和 Notifications

逻辑流程是我将收到许多消息,这些消息将存储到Notifications 表中。每隔一段时间,我都会将所有通知按一个公共标识符分组,然后将一行存储到 Records 表中,并将该标识符作为主键。

问题是,稍后我可能仍会收到具有相同标识符的通知,但如果我已经为其创建了记录,我想忽略它们。

所以我的问题是——只有当标识符没有出现在Records 表中时,有没有一种有条件地插入notifications 的好方法?我正在考虑一个“反向外键”,如果列确实出现在另一个表中,它将无法插入。

我知道这个 SQL 不起作用,但我正试图让这样的事情发生:

INSERT INTO notifications (id, notification, timestamp) 
values (:id, :notification, now()) 
WHERE records DOES NOT HAVE :id

【问题讨论】:

    标签: sql postgresql foreign-keys subquery sql-insert


    【解决方案1】:

    您可以使用insert ... select 声明来表达这一点:

    INSERT INTO notifications (id, notification, timestamp) 
    SELECT s.*, now()
    FROM (VALUES (:id, :notification)) AS s(id, notification)
    WHERE NOT EXISTS (SELECT 1 FROM records r WHERE r.id = s.id)
    

    【讨论】:

      猜你喜欢
      • 2016-03-27
      • 2019-07-29
      • 2022-11-07
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2011-10-17
      • 2017-05-23
      • 1970-01-01
      相关资源
      最近更新 更多