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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章