索引
#### 对数据库表的一列或者多列的值进行排序的一种结构(Btree方式)
- 优点:可以加快数据检索速度
- 缺点:占用物理储存空间;当对表中数据更新时,索引需要动态维护,降低数据维护速度
索引示例:
- 开启运行时间检测(
show variables like '%pro%;'
)(set profiling = 1;
) - 执行查询语句(无索引)(
select name from student where name = 'Tom2000000'
) - 查看执行时间(
show profiles;
) - 在字段创建索引(
create index name on student(name)
) - 再执行查询语句(
select name from student where name = 'Tom2000000'
) - 查看执行时间(
show profiles;
)
普通索引和唯一索引
可设置多个字段
普通索引:字段值无约束,key标志为 mul(`desc 表名;`)
唯一索引:字段值不允许重复,但可为null,key标志为uni
那些字段创建索引:经常用来查询的字段,where条件判断字段,order by排序的字段
- 创建表时
create table 表名(字段名 数据类型,index(字段名),unique(字段名));
- 已有表中创建
create [unique] index 索引名 on 表名(字段名);
- 查看索引
desc 表名;
show index from 表名\G;
- 删除索引
drop index 索引名 on 表名
主键(pri)和自增长(auto_increment)
- 创建表时
create table 表名() auto_increment=值;
#设置自增长的起始值
- 已有表添加主键
alter table 表名 add primary key(id);
- 已有表操作自增长属性
alter table 表名 modify id int auto_increment;
alter table 表名 auto_increment=起始值;
- 删除
alter table 表名 modify id int;
#首先删除自增长alter table 表名 drop primary key;
#再删除主键