这里的主键包括唯一约束
虽然建立主键必须要有个一个索引,很多时候还是唯一索引,我们就误以为唯一性是靠唯一索引来实现的。实际并不是这样的,因为主键可以关联到一个Non-Unique Index,同样来保证唯一性。所以我猜测(没有证据),唯一约束必须要有一个index仅仅是从效率上需求,插入一行的时候不用每次都做一次全表扫描。我有5点旁证:
1 唯一约束和唯一索引在oracle数据库单独存在
2 唯一约束可以不用唯一索引(效率怎么样就不知道呢)
3 没有唯一约束只有唯一索引,也可以保证唯一性
4 Disable或drop唯一约束的时候,对应的唯一索引也会被drop掉,但我们可以用keep index来保留,但是这样它还会保证唯一性,drop和disable就没有意义了
-
SQL> alter table emp add primary key (id);
-
-
Table altered.
-
-
SQL> select index_name,index_type,UNIQUENESS from user_indexes;
-
-
INDEX_NAME INDEX_TYPE UNIQUENES
-
------------------------------ --------------------------- ---------
-
SYS_C003774 NORMAL UNIQUE
-
-
SQL> alter table emp drop constraint SYS_C003774 keep index;
-
-
Table altered.
-
-
SQL> select index_name,index_type,UNIQUENESS from user_indexes;
-
-
INDEX_NAME INDEX_TYPE UNIQUENES
-
------------------------------ --------------------------- ---------
-
SYS_C003774 NORMAL UNIQUE
5 如果约束定义为DEFERRABLE,还必须使用Non-Unique Index
-
SQL> alter table emp add primary key (id) INITIALLY DEFERRED DEFERRABLE;
-
-
Table altered.
-
-
SQL> select CONSTRAINT_NAME,CONSTRAINT_TYPE,DEFERRABLE,DEFERRED from user_constraints;
-
-
CONSTRAINT_NAME C DEFERRABLE DEFERRED
-
------------------------------ - -------------- ---------
-
SYS_C003778 P DEFERRABLE DEFERRED
-
-
SQL> insert into emp values (3,3);
-
-
1 row created.
-
-
SQL> insert into emp values (3,3);
-
-
1 row created.
-
-
SQL> commit;
-
commit
-
*
-
ERROR at line 1:
-
ORA-02091: transaction rolled back
-
ORA-00001: unique constraint (ORACLE_OCM.SYS_C003778) violated
-
-
-
SQL> alter table emp drop primary key;
-
-
Table altered.
-
-
SQL> drop index idx01;
-
-
Index dropped.
-
-
SQL> create unique index idx01 on emp(id);
-
-
Index created.
-
-
SQL> alter table emp add primary key (id) INITIALLY DEFERRED DEFERRABLE;
-
alter table emp add primary key (id) INITIALLY DEFERRED DEFERRABLE
-
*
-
ERROR at line 1:
-
ORA-01408: such column list already indexed
阅读(1728) | 评论(0) | 转发(0) |