使用 PSQL 添加多列约束的最佳方法

Best way to add multi column constraint with PSQL

我有空 table :

CREATE TABLE availability (
    id SERIAL PRIMARY KEY,
    user_id int REFERENCES users(id) NOT NULL,
    address_id int REFERENCES addresses(id) ON DELETE CASCADE,
    day_of_week int NOT NULL,
    start_mn int,
    end_mn int,
    EXCLUDE using gist (user_id WITH =, day_of_week WITH =, (array[start_mn, end_mn]) WITH &&)
)

在我的地址 table 中,我还有一个 user_id 字段引用了 users(id)

确保插入的相关地址与可用性 table 中的地址相同 user_id 的最佳方法是什么?

我尝试寻找触发器或函数但没有成功,我想知道是否有处理此问题的惯用方法。

您将在 addresses 中对 (id, user_id) 创建一个 UNIQUE 约束。

然后创建复合外键:

CREATE TABLE availability (
   ...,
   FOREIGN KEY (address_id, user_id) REFERENCES addresses (id, user_id)
);