存储引擎、索引

存储引擎、索引

 

存储引擎

定义:

  就是数据库存储数据的技术,能够类比成发动机引擎,不一样的引擎性能各不相同html

分类*****

最多见的两个存储引擎是innodb和myisam,区别以下:sql

一、innodb数据库

  --一、(默认版本是5.5及以上)数据结构

  --二、支持事务函数

  --三、不支持全文索引工具

  --四、索引和数据在同一文件中,.ibdpost

     表的结构是在.frm文件中性能

二、myisamurl

  --一、(默认版本5.5如下,主要5.3用的人最多)spa

  --二、不支持事务

  --三、支持全文索引

  --四、.frm:表结构

     .MYD:表数据

     .MYI:表索引

三、memory(不经常使用)

ps:innodb不支持全文索引

  国内广泛用的全文索引  sphinx(斯芬克斯)

索引

类比

至关于新华字典的目录,咱们能够把索引理解成一个特殊的文件,

若是没有这个文件,查询是从前日后查找数据的,

若是有这个文件,会按照一种特殊的数据结构(二叉树)查找数据

做用

加快查询的数据

分类

一、主键索引:加快查询  +  不能重复  +  不能为空  primary key

二、惟一索引:加快查询  +  不能重复   unique(列名)

   联合惟一索引:加快查询 + 不能重复  unique(列名1,列名2,..)

三、普通索引:加快查询  index(列名)

建立及删除

建立

一、建表时建立

复制代码
create table t1(
# 主键的建立
id int auto_increment primary key,  
name varchar(32) not null default '',
age int not null default 0,
num int not null default 0,
# 联合惟一索引的建立
unique uni_name_num (name,age),  
# 普通索引的建立
index ix_age (age)            
).engine=innodb charset=utf8;
复制代码

二、表存在后建立

复制代码
# 主键索引的建立
alter table t1 change id id int auto_increment primary key
# 惟一索引的建立
create unique index ix_name on t1(name)
create unique index ix_name_age on t1(name,age)
# 普通索引的建立
create index ix_age on t1(age)
复制代码

删除

# 若是主键是自增的,则没法删除,要先取消自增再删除
alter table t1 change id id int;
alter table t1 drop primary key;

# 删除惟一索引和普通索引同样
drop index ix_name on t1;

索引的优缺点

优势:

  查询数据速度快

缺点:

  版本5.3如下:

    删除和修改数据的速度会变得很慢,会重构索引

  版本5.5以上:

    删除和修改数据的速度不是特别慢

 

索引的使用

  数据库表中添加索引后确实会让查询速度起飞,但前提必须是正确的使用索引

  来查询,若是以错误的方式使用,则即便创建索引也不会生效

错误索引案例

复制代码
# -like '%xx'
    select * from t1 where name like '%cn%';

# -使用函数
    select * from t1 where reverse(name) = 'xxx';

# -order by
    select email from t1 order by name desc;
    # 当根据索引排序时,选择的映射若是不是索引,则不走索引
    # 特别的:若是对主键排序,则仍是走索引
        select * from t1 order by id;
复制代码

explain  工具

  查看sql语句是否用得上索引,或者查看sql执行效率的工具

  给执行的sql语句出一个报告,经过此报告来判断sql语句的

  执行效率和效果(不必定都按结果上来)

SQL语句的规则

  一、不建议使用like进行搜索

  二、不建议使用函数

  三、组合索引最左前缀

    若是组合索引为:(name,email)

    where name and email     --使用索引

    where name           --使用索引

    where email           --不适用索引

explain查询以后参数的含义(了解)

相关文章
相关标签/搜索