主键就是能够唯一标识表中某一行的属性或属性组,一个表只能有一个主键,但可以有多个候选索引。
因为主键可以唯一标识某一行记录,所以可以确保执行数据更新、删除的时候不会出现张冠李戴的错误。主键与外键构成参照完整性约束,防止出现数据不一致。数据库在设计时,主键起到了很重要的作用。主键更适合那些不容易更改的唯一标识,如自动递增列、身份证号等。
主键可以保证记录的唯一和主键域非空,数据库管理系统对于主键自动生成唯一索引,所以主键也是一个特殊的索引。两者的详细分析如下:
(1)主键是一种约束,唯一索引是一种索引,两者在本质上是不同的。
(2)主键一定是唯一性索引,唯一性索引并不一定就是主键。
(3)一个表中可以有多个唯一性索引,但只能有一个主键。
(4)唯一索引可以为空,但是空值只能有一个,主键索引不能为空。
(5)主键和索引都是键,不过主键是逻辑键,索引是物理键,意思就是主键不实际存在,而索引实际存在在数据库中,会占用磁盘。
1、查看索引
show index from system_operation;
2、创建唯一索引
create unique index unique_index_operation_name on system_operation(operation_name);
create unique index unique_index_operation_code on system_operation(operation_code);
create unique index unique_index_operation_nameandcode on system_operation(operation_name,operation_code);
3、删除唯一索引
drop index unique_index_operation_name on system_operation;
drop index unique_index_operation_code on system_operation;
drop index unique_index_operation_nameandcode on system_operation;
4、将UNIQUE约束添加到已存在的表中
alter table system_operation constraint unique_index_operation_name unique(operation_name);
alter table system_operation constraint unique_index_operation_code unique(operation_code);
alter table system_operation constraint unique_index_operation_nameandcode unique(operation_name,operation_code);
5、解除唯一索引
alter table system_operation drop index unique_index_operation_name;
alter table system_operation drop index unique_index_operation_code;
alter table system_operation drop index unique_index_operation_nameandcode;