fagz

7.28 索引的使用 ,SQL提示

最左前缀法则
如果索引了多列(联合索引),要遵守最左前缀法则。最左前缀法则指的是查询从索引的最左列开始,并且不能跳过索引中的列。如果跳跃某一列,索引将部分失效(后面的字段索引失效)。#最左法则跟放的位置没有关系,重要的是必须存在。

范围查询
联合索引中,出现范围查询(>,<),范围查询右侧的列索引失效。
例:explain selectfrom tb_user where profession='计算机科学与技术' and age>30 and status='0';#错误
explain select
from tb_user where profession='计算机科学与技术' and age>=30 and status='0';#正确

字段运算
对字段进行函数运算索引失效。

字符串不加引号
字符串类型字段使用时,不加引号,索引将失效。

模糊查询
如果仅仅是尾部模糊匹配,索引不会失效。如果是头部模糊匹配,索引失效。
例:expain selectfrom tb_user where profession like '软件%';
expain select
from tb_user where profession like '%工程';
expain select*from tb_user where profession like '%工%';

or连接的条件
用or分割的条件,如果or前的条件中的列有索引,而后面的列中没有索引,那么涉及的索引都不会被用到。

SQL提示
SQL提示,是优化数据库的一种重要手段,简单来说,就是在SQL语句中加入一些人为的提示来达到优化操作的目的。
use index:
explain selectfrom tb_user use index(idx_user_pro)where profession='软件工程';
ignore index:
explain select
from tb_user ignore index(idx_user_pro)where profession='软件工程';
force index:
explain select*from tb_user force index(idx_user_pro)where profession='软件工程';

覆盖索引
尽量使用覆盖索引(查询使用了索引,并且需要返回的列,在该索引中已经全部能够找到)减少select*,即不需要回表查询。

前缀索引
当前字段类型为字符串时,有时候需要索引很长的字符串,这会让索引变得很大,查询时,浪费大量的磁盘IO,影响查询效率。此时可以只将字符串的一部分前缀,建立索引,这样可以大大节约索引空间,从而提高索引效率。
语法:
create index idx_xxxx on table_name(column(n));
前缀长度
可以根据索引的选择性来决定,而选择性是指不重复的索引值(基数)和数据表的记录总数的比值,索引选择性越高则查询效率越高,唯一索引的选择性是1,这是最好的索引选择性,性能也是最好的。
select count(distinct email)/count( * ) from tb_user;
select count(distinct substring(email,1,5))/count( * ) from tb_user;

posted on 2025-07-28 18:12  fagz  阅读(6)  评论(0)    收藏  举报

导航