postgres-具有多列和空值的唯一约束

时间:2020-11-04 19:40:35

标签: postgresql psql

解决此问题的最佳方法是什么。我定义了以下表测试:

  Column    |       Type        | Collation | Nullable | Default 
-------------+-------------------+-----------+----------+---------
 id          | integer           |           | not null | 
 name        | character varying |           | not null | 
 description | character varying |           |          | 
 a_id        | character varying |           | not null | 
 b_id        | character varying |           |          | 
Indexes:
    "test_pkey" PRIMARY KEY, btree (id)
    "test_ukey" UNIQUE CONSTRAINT, btree (name, a_id, b_id)
Foreign-key constraints:
    "test_a_id_fkey" FOREIGN KEY (a_id) REFERENCES testa(id) ON DELETE CASCADE

请注意,“ id”和“ name”不能为NULL,而b_id可以为NULL,这对业务逻辑具有特殊含义。如果处理NULL是一个问题,也可以将其设置为一些默认值。根据唯一的约束,我只允许对同一条目(名称,a_id,b_id)进行输入。但是,我想允许/禁止以下插入:

   id       name        a_id        b_id
    1       admin       a_1               --> allowed (only one entry if there is no existing same row as b_id not null)
    2       admin       a_1               --> not allowed since row 1 already exist (admin, a_1, null)
    3       admin       a_1         b_1   --> not allowed since row 1 already exist (admin, a_1, null)
    4       operator    a_1         b_1   --> allowed
    5       operator    a_1         b_2   --> allowed
    6       operator    a_1               --> not allowed since row 4 or 5 already exists
    7       operator    a_2               --> allowed (only one entry if there is no existing same row as b_id not null)

是否可以通过创建/修改唯一约束或索引来实现? 我知道可以使用触发器来避免这种情况。

0 个答案:

没有答案
相关问题