一、索引的分类:
- 普通索引
- 唯一性索引:与普通索引基本相同,但是索引列的所有值只能出现一次,必须唯一。
- 主键(主索引):主键一般在创建表的时候指定,也可以通过修改表的方式加入主键,但每个表只有一个主键
- 全文索引:只能在VARCHAR或TEXT类型的列上创建
表级约束:
create table test2(id int primary key);
列级约束:
create table test3(id int primary key(id));
二、创建普通索引(属性值可以重复的)
- create index 语句创建
为一个表中的一列创建索引:
在name列中创建一个ID普通索引
①create index idx_name on test(name);
②desc test;
展示创建的索引内容:
show index from test;
三、创建唯一索引(属性值不能重复,比较适合候选码)
1.在age列中创建一个唯一索引:
create unique index idx_age on test(age);
2.表不存在时,可以创建:
创建表的同时创建唯一索引:
①create table test4(id int,name varchar(10),
-> primary key(id),
-> unique (name)
-> );
② show index from test4;
insert into test4 values(1,'tom'); //添加一条数据值
四、比较几种索引:
- 一个表只能创建一个的索引是:主键(索引)
- 一个表可以创建多个普通或者唯一索引
- 创建为索引的属性列值必须唯一的是:主索引和唯一索引,值可以重复的是普通索引
五、命名完整性约束:
创建表给表完整性约束指定约束名:
创建表时为索引起名:
①create table test5(id int ,name varchar(10),
-> constraint mypri primary key(id),
-> constraint myuiq unique(name)
-> );
② show index from test5;
六、删除主键索引:
可以根据索引名称,进行删除操作:
方法一:(删除主键(索引),不需要使用名称)
①alter table test5 drop primary key;
② show index from test5;
方法二:删除其他索引,需要使用名称
alter table test5 drop index myuiq; //不能进行重复删除