PostgreSQL - 在另一个 table /反向外键中不存在的地方插入?

PostgreSQL - Insert where not exists in another table / Reverse Foreign Key?

我在 PostgreSQL 数据库中有两个 table:RecordsNotifications

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

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

所以我的问题是 - 只有当标识符没有出现在 Records table 中时,是否有一种好方法可以有条件地插入 notifications?我在想一个“反向外键”,如果一个列确实出现在另一个 table.

中,它将无法插入

我知道这 SQL 行不通,但我正在努力让这样的事情发生:

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

您可以用 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)