键值的种类:普通索引(index)、唯一索引(unique)、主键(primary key)、外键(foreign key)、全文索引(fulltext)。
一 . 普通索引的使用
-
普通索引介绍
用来给字段值排队,加快对数据库查询的速度,配置后占用物理存储空间;主要类型有:Btree 、B+tree 、hash。
-
使用规则
一个表可以有多个index字段,设置为index的字段的值允许重复,且可以赋NULL值;通常将作为查询条件的字段设置为index字段,index字段的标志是MUL。
-
创建索引的方式
建表时创建索引: create table testdb.test( id int(6), name char(10), group char(10), sex enum(girl,boy), index(id), index(name) ); 在已有的表中创建索引: create index index_name on testdb.test(id); index_name:索引名称
-
查看索引信息
show index from testdb.test \G; // \G按行显示 drop index 字段名 on testdb.test; // 删除索引
二 . 主键及复合主键的使用
-
使用规则
在一个表中只能创建一次主键(primary key)字段;当多个字段都作为主键时,必须一起创建,称为复合主键;对于设置为主键的字段值不允许重复、不允许赋NULL值;通常把表中唯一标识记录的字段设置为主键(记录编号的字段),主键字段的标志为PRI。主键通常与auto_increment 连用 实现自增。
-
创建及删除主键
建表时创建主键: create table testdb.test( id int(6) primary key, //设置为主键 name char(10), group char(10) ); 在已有表中创建主键: alter table testdb.test add primary key (id); 删除主键: alter table testdb.test drop primary;
-
创建及删除复合主键:
建表时创建: create table testdb.test( id int, name char(10), group char(10), primary key(id,name) //创建复合主键 ); 在已有表中创建: alter table testdb.test add primary key(id,name); 删除复合主键: alter table testdb.test drop primary key;
三 . 外键的使用
-
使用规则
在插入记录时,字段值在另一个表的字段值范围内选择;表字段类型要一致,被参照字段必须是索引类型的一种;使用外键的前提是该表的引擎必须是innodb。 -
创建及删除外键
创建外键: create table testdb.test( id int, name char(10), group char(10), foreign key(name) references 参照表名(字段名)//指定外键及参照表 on update cascade //同步更新 on delete cascade //同步删除 )engine=innodb; //指定存储引擎 删除外键: alter table testdb.test drop foreign key 外键名称;