MySQL索引与完整性约束
mysql> create table test2(id int primary key);//列级约束
mysql> create table test3(id int,primary key(id));//表级约束
1、创建普通索引(属性值可以重复)
mysql> create index idx_name on test(name) ;
-
mysql> desc test;
mysql> show index from test;
2、创建唯一索引(属性值不能重复,比较适合候选码)
mysql> create unique index idx_age on test(age);
3、表不存在时,可以创建为:
mysql> create table test4(id int,name varchar(10),
-> primary key(id),
-> unique(name) //建表的同时创建唯一索引
-> );
mysql> insert into test4 values(1,'tom');(√)
mysql> insert into test4 values(2,'tom');(×)
比较几种索引
1、一个表只能创建一个的索引是:主键(索引)
2、一个表可以创建多个普通或者唯一索引
3、创建为索引的属性列值必须唯一的是:主索引和唯一索引,值可以重复的是普通索引
为索引命名
mysql> create table test5(id int,name varchar(10),
-> constraint mypri primary key(id),
-> constraint myuiq unique(name)
-> );
删除索引(可以更加索引名称,进行删除操作):
删除主键(索引),不需要使用名称
mysql> alter table test5 drop primary key;
删除其他索引,需要使用名称
mysql> alter table test5 drop index myuiq;
或者是mysql> drop index myuiq on test5;