向引用另一个 table 的记录子集的 table 添加约束

Adding constraint to a table referencing a subset of records of another table

假设我有以下 tables:

User(user_id, name, age,...)
Job(job_id, salary, user_id)

我想对 Job 进行约束,以便每当工作的薪水 > 20,000 时,从事该工作的用户年龄必须 >= 18。我已经尝试了 CHECK 约束但它似乎只适用于单个 table?

没错,检查约束仅适用于单个 table。 您必须使用触发程序来阻止不需要的数据,请参阅下面的 link 触发程序。

Postgresql Documentation - Trigger Procedures

您可以使用 user-defined 函数执行此操作。该函数可以在其他 table.

中查找值

我不一定推荐这种方法。对于许多应用程序,我将 insert/update 语句包装在存储的 procedure/function 中并将逻辑放在那里。然而,这在没有触发器的情况下是可能的。