chan

朝生暮死不足笑 但悲百年不足道

【MySQL】索引


索引原理:底层是因为基于B+Tree的数据结构存储

在创建数据库表的时候,可以指定不同的引擎。

  • myisam引擎,非聚簇索引(数据 和 索引结构 分开存储)
  • innodb引擎,聚簇索引(数据 和 主键索引结构存储在一起)

常见索引

  • 主键索引:加速查找、不能为空、不能重复。 + 联合主键索引
  • 唯一索引:加速查找、不能重复。 + 联合唯一索引
  • 普通索引:加速查找。 + 联合索引

会有一些特殊的情况,让我们无法命中索引(即使创建了索引)

- 类型不一致

  ```sql
  select * from big where name = 123;		-- 未命中
  select * from big where email = 123;	-- 未命中
  
  特殊的主键:
  	select * from big where id = "123";	-- 命中
  ```

- 使用不等于

  ```sql
  select * from big where name != "武沛齐";				-- 未命中
  select * from big where email != "wupeiqi@live.com";  -- 未命中
  
  特殊的主键:
  	select * from big where id != 123;	-- 命中
  ```

- or,当or条件中有未建立索引的列才失效。

  ```sql
  select * from big where id = 123 or password="xx";			-- 未命中
  select * from big where name = "wupeiqi" or password="xx";	-- 未命中
  特别的:
  	select * from big where id = 10 or password="xx" and name="xx"; -- 命中
  ```

- 排序,当根据索引排序时候,选择的映射如果不是索引,则不走索引。

  ```sql
  select * from big order by name asc;     -- 未命中
  select * from big order by name desc;    -- 未命中
  
  特别的主键:
  	select * from big order by id desc;  -- 命中
  ```

- like,模糊匹配时。

  ```sql
  select * from big where name like "%u-12-19999";	-- 未命中
  select * from big where name like "_u-12-19999";	-- 未命中
  select * from big where name like "wu-%-10";		-- 未命中
  
  特别的:
  	select * from big where name like "wu-1111-%";	-- 命中
  	select * from big where name like "wuw-%";		-- 命中
  ```

- 使用函数

  ```sql
  select * from big where reverse(name) = "wupeiqi";  -- 未命中
  
  特别的:
  	select * from big where name = reverse("wupeiqi");  -- 命中
  ```

- 最左前缀,如果是联合索引,要遵循最左前缀原则。

  ```sql
  如果联合索引为:(name,password)
      name and password       -- 命中
      name                 	-- 命中
      password                -- 未命中
      name or password       	-- 未命中
  ```

  

常见的无法命中索引的情况就是上述的示例。

评论
还没有评论
    发表评论 说点什么