UNIQUE 约束,其中 NULL 是一个有效值

UNIQUE constraint where NULL is one valid value

Inn PostgreSQL 我想要一个多列 UNIQUE 约束,其中一列可以恰好为 NULL 一次。

到目前为止我尝试过的:

ALTER TABLE customexternalemail 
ADD CONSTRAINT customexternalemail_sp_emaildomain_unique 
    UNIQUE(serviceproviderid, emailprefix, emaildomainid);

其中serviceprovideridemaildomainid是BIGINT,emailprefix是TEXT。 emaildomainid 是唯一允许 NULL 的列,也是我遇到问题的列。

基本上,我只想允许一个条目匹配 serviceprovideridemailprefixemaildomainid 的组合,其中 emaildomainid 可以是 BIGINT 值或 NULL .目前(具有上述约束),如果 emaildomainid 为 NULL,它将接受重复,但如果 emaildomainid 不为 NULL,则它必须是唯一的。

您可以创建两个 partial indexes. They are supported since version 7.2,它于 2002 年 2 月发布。

emaildomainid 不为空时,这将检查三列的任何组合是否唯一:

CREATE UNIQUE INDEX customexternalemail_sp_emaildomain_unique_not_null 
    ON customexternalemail (serviceproviderid, emailprefix, emaildomainid)
    WHERE emaildomainid IS NOT NULL;

这将确保对于 emaildomainid 具有空值的任何行,组合 (serviceproviderid, emailprefix) 将是唯一的:

CREATE UNIQUE INDEX customexternalemail_sp_emaildomain_unique_null 
    ON customexternalemail (serviceproviderid, emailprefix)
    WHERE emaildomainid IS NULL;