MySQL数据库:索引、主键、自增长

索引

#### 对数据库表的一列或者多列的值进行排序的一种结构(Btree方式)
  • 优点:可以加快数据检索速度
  • 缺点:占用物理储存空间;当对表中数据更新时,索引需要动态维护,降低数据维护速度

索引示例:

  1. 开启运行时间检测(show variables like '%pro%;')(set profiling = 1;)
  2. 执行查询语句(无索引)(select name from student where name = 'Tom2000000')
  3. 查看执行时间(show profiles;)
  4. 在字段创建索引(create index name on student(name))
  5. 再执行查询语句(select name from student where name = 'Tom2000000')
  6. 查看执行时间(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;#再删除主键
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章