数据库索引

1.工作原理:

数据库索引是怎么工作的呢?可以简单理解为我们要看一本书的某一个知识点,如果你从第一页开始一页页的找的话,是不是很慢呢,但是如果有目录的话,那么你就可以在目录中查找你想要看的内容所在的页数,然后按照这个指定的页数就可以找到你想要看的内容。这样是不是就快多了。

索引的工作原理类似:首先在索引中找到对应值,然后根据对应匹配的索引记录找到对应的数据行。比如在name列上建立索引,则mysql将使用该索引找到name为qiu的行,也就是说mysql先在索引上按值查找,然后返回包含该值的所有数据行。

这样的好处是可以减少服务器需要扫描的数据量,提高查询效率。

2.创建索引和删除索引

如果表my_db已经存在, create index my_index on my_db(column_name)

如果创建新表时创建索引,则方法如:

create table mydb(
      id Int(6) not null auto_increment,
      last_name vachar(50) not null,
      first_name vachar(50) not null,
      job vachar(50) not null,
      age vachar(50) not null,
      addresse vachar(50) not null,
       primary key(id),
       key 'my_index'(last_name,first_name,age)
)
 删除索引:
alter table my_db drop index my_index
 
3.索引在以下几种情况下有效:
(1).全值匹配:
和索引中所有的列进行匹配,如select * from mydb where last_name=qiu and first_name=yaoyao and age=10
(2).匹配最左前缀:
如只使用索引的第一列  select * from mydb where last_name=qiu
(3).匹配列前缀: 
select * from mydb where last_name like "q%"  正确
select * from mydb where last_name like "%u"   索引失效
(4).匹配范围值   :
查找last_name是w开头的 select * from mydb where last_name like “w%”
(5).精确匹配某一列并范围匹配另外一列
查找last_name="wu",first_name在qiu和yang之间的人,但要注意的是,如果索引的某一列使用了范围匹配,则这列之后的列就不生效了。 比如 select * from mydb where last_name="wu"  and first_name between "qiu" and "yang"  and age=10 那么会筛选出last_name="wu",first_name在qiu和yang之间,但是年龄任意(而不是等于10岁)的人
(6).只访问索引的查询
 
4.需要注意的是:
(1).如果不是按照索引的最左列开始查询,则无法使用索引。例如上述的无法查找where first_name =weiyao,因为索引中first_name的前一列没有用来查询。同样也没法查找last_name like“%iu”的,因为这个列匹配的不是列的前缀
(2).不能跳过索引中的某一列,比如说查询的时候,条件是where last_name=“qiu” and age=24, 
(3).如果查询的某个列用的是范围查询,则其右边所有列都无法按照索引优化来查找。比如就上面说过的一个例子,where  last_name like“q%” and first_name=weiyao,则这里的first_name是不能按照索引来查找的
 
 
原文地址:https://www.cnblogs.com/weiweiyao/p/4478750.html