有没有办法将外键引用限制到另一列,将自定义规则放在这个引用上?

Is there a way to restrict foreign keys references to another column putting custom rules on this references?

我有三个 table,它们都是我系统的用户类型:masterunitemployee

基本上,所有这些 table 都有一个引用 user(id) 的列(所有这些 table 也有一个 user 行,其中包含一般数据)。

这个问题的要点是employeetable,其中有一栏叫做employer_id(这个雇员的雇主是谁),其中指的是user(id).我的问题是我想将 employer_id 外键引用限制为仅 master xor unit,而不是两者,而不是既不是主人也不是单位的用户。但是 employer_id 引用 user(id) 的事实允许系统的任何类型的用户都可以是该雇员的雇主。

有没有办法限制外键 table 引用?

是的,您可以在 insert/update 之前创建一个触发器来检查是否存在 user_idemployer_id 的值匹配的员工。如果存在这样的记录,则抛出异常。参见:https://www.postgresql.org/docs/9.1/plpgsql-trigger.html