Mar*_*ney 2 postgresql unique-constraint
PostgreSQL旅馆我想要一个多列UNIQUE约束,其中的一列可以完全为NULL。
到目前为止,我已经尝试过:
ALTER TABLE customexternalemail
ADD CONSTRAINT customexternalemail_sp_emaildomain_unique
UNIQUE(serviceproviderid, emailprefix, emaildomainid);
Run Code Online (Sandbox Code Playgroud)
其中serviceproviderid和emaildomainid是BIGINT,并且emailprefix是TEXT。emaildomainid是唯一允许使用NULL的列,也是我遇到问题的列。
基本上,我想只允许一个项目相匹配的组合serviceproviderid,emailprefix以及emaildomainid,在那里emaildomainid可能是一个BIGINT值或NULL。当前(具有上述约束),如果emaildomainid为NULL,它将接受重复,但是如果emaildomainid不为NULL,则它必须是唯一的。
您可以创建两个部分索引。自2002年2月发布的7.2版以来,已支持它们。
这将检查在emaildomainid不为null的情况下,三列的组合是否唯一:
CREATE UNIQUE INDEX customexternalemail_sp_emaildomain_unique_not_null
ON customexternalemail (serviceproviderid, emailprefix, emaildomainid)
WHERE emaildomainid IS NOT NULL;
Run Code Online (Sandbox Code Playgroud)
这将确保对于的任何值为null的行emaildomainid,其组合(serviceproviderid, emailprefix)都是唯一的:
CREATE UNIQUE INDEX customexternalemail_sp_emaildomain_unique_null
ON customexternalemail (serviceproviderid, emailprefix)
WHERE emaildomainid IS NULL;
Run Code Online (Sandbox Code Playgroud)