返回数说广场
0
问:一张大表有一个字段创建为普通索引(没有重复值),如果快速把这个字段变为主键索引
答:1.删除索引,创建主键,显然对于大表效率很低。
2.直接在该字段上创建
alter table t add constraint t_id_pk primary key(id);
原理:主键就是生成一个与外键相关的约束,产生一个能保证唯一性的索引。
过程如下:
SQL> create table a as select * from dba_objects;
Table created.
SQL> create index idx_a on a(object_id);
SQL> alter table a add constraint a_id_pk primary key(object_id);
Table altered.
如果该字段索引不唯一,会怎么样
SQL> create table b as select * from dba_objects;
Table created.
SQL> insert into b select * from dba_objects;
89346 rows created.
SQL> commit;
Commit complete.
SQL> create index idx_b on b(object_id);
Index created.
SQL> alter table b add constraint b_id_pk primary key(object_id);
alter table b add constraint b_id_pk primary key(object_id)
*
ERROR at line 1:
ORA-02437: cannot validate (T1.B_ID_PK) - primary key violated
0

259
分享
评论
热门数说