当另一列为null或不为null时,如何添加约束,例如一列具有特定值?

时间:2018-12-18 08:29:39

标签: postgresql knex.js

这是我的种子数据行:

{ organization_id: 1, parent_id: null, organization_type: OrganizationType.ORG },
{ organization_id: 2, parent_id: 1, organization_type: OrganizationType.CLIENT },
{ organization_id: 3, parent_id: 1, organization_type: OrganizationType.CLIENT }

我想向organizations表添加约束。

此约束具有以下规则:

    organization_typeOrganizationType.ORG时,
  1. parent_id应该为null

  2. organization_type不是OrganizationType.CLIENT

    时,
  3. parent_id应该是null

我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用检查约束:

create table organizationns
(
  <other columns>, 
  parent_id integer,
  organization_type varchar(50) not null,
  constraint check_org_type 
    check (   (parent_id is null     and organization_type = 'ORG')
           or (parent_id is not null and organization_type = 'CLIENT')) 
);

但是在这种情况下,organization_type列似乎没有用,因为您总是可以从parent_id派生它(例如,通过视图)