pgsql 组合唯一约束或唯一索引 null失效的情况

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL.

解决方案:
给对应字段可能为空的列定义一个特殊值来替代NULL,比如数字类型使用000值,字符串类型使用特定字符串。

具体是什么意思?例子来解释一下:

create table lych001(id int,name varchar(100),class int);
alter table lych001 add constraint lych_cons unique(id,name,class);
insert into lych001 values(1,'aaa',null); 在PG中可以多次执行不会报唯一约束错误,但是在ORACLE中这个会报错。insert这条SQL,任何一个字段出现null,其他字段相同,都可以重复插入

oracle、PG以下逻辑相同:

创建唯一约束会在Oracle中创建一个Constraint,同时也会创建一个该约束对应的唯一索引。
创建唯一索引只会创建一个唯一索引,不会创建Constraint

猜你喜欢

转载自blog.51cto.com/2012ivan/2619362
今日推荐