MySQL:主键与唯一索引

主键就是能够唯一标识表中某一行的属性或属性组,一个表只能有一个主键,但可以有多个候选索引。

因为主键可以唯一标识某一行记录,所以可以确保执行数据更新、删除的时候不会出现张冠李戴的错误。主键与外键构成参照完整性约束,防止出现数据不一致。数据库在设计时,主键起到了很重要的作用。主键更适合那些不容易更改的唯一标识,如自动递增列、身份证号等。

主键可以保证记录的唯一和主键域非空,数据库管理系统对于主键自动生成唯一索引,所以主键也是一个特殊的索引。两者的详细分析如下:
(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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王小二(海阔天空)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值