创建主键时,所相应的列假设没有索引。数据库默认会自己主动创建一个索引;假设对于列有索引,那么创建主键不会再创建索引。这里要注意,列值必须满足主键的要求(唯一,非空)。简单測试例如以下:
SQL> create table wxlun_pri(a number);
Table created.
SQL> alter table wxlun_pri add constraint PRIMARY_KEY_REPLY primary key (a); ------创建主键约束
Table altered.
SQL> select index_name from user_indexes where table_name='WXLUN_PRI'; ------默认生成索引
INDEX_NAME
------------------------------
PRIMARY_KEY_REPLY
SQL> alter table wxlun_pri drop constraint PRIMARY_KEY_REPLY;
Table altered.
SQL> select index_name from user_indexes where table_name='WXLUN_PRI';
no rows selected
SQL> create index idx_wxlun_pri on wxlun_pri(a); ------创建一个一般索引,測试有反复值时加入主键约束
Index created.
SQL> insert into wxlun_pri values(1);
1 row created.
SQL> /
1 row created.
SQL> commit;
Commit complete.
SQL> select * from wxlun_pri;
A
----------
1
1
SQL> alter table wxlun_pri add constraint PRIMARY_KEY_REPLY primary key (a); ------原索引有反复值。加入主键约束失败
alter table wxlun_pri add constraint PRIMARY_KEY_REPLY primary key (a)
*
ERROR at line 1:
ORA-02437: cannot validate (WXLUN.PRIMARY_KEY_REPLY) - primary key violated
删除反复值。加入主键约束
1 row deleted.
SQL> commit;
Commit complete.
SQL> select * from wxlun_pri;
A
----------
1
SQL> alter table wxlun_pri add constraint PRIMARY_KEY_REPLY primary key (a); ------成功
Table altered.
SQL> select index_name from user_indexes where table_name='WXLUN_PRI';
INDEX_NAME
------------------------------
IDX_WXLUN_PRI
SQL> drop table wxlun_pri;
Table dropped.
SQL>