暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MySQL优化-索引优化

编程经验共享 2023-02-08
62

今天我们来说一说索引优化。首先我们来说一说什么情况需要建立索引吧?

1.当使用不以通配符开始的like模糊查询时也可以使用索引,反之就不能使用索引了

Select * from table1 where username like ‘pack%;  # username字段会走索引 

Select * from table1 where username like%pack%; # username字段不会走索引

复制

2,一个索引字段的前缀使用了order by或者group by时也会走索引:

Select * from table2 order by field1;
复制

3.查找某个字段的最大值和最小值会走索引查询

Select min(score),max(score) from table4 where class_id = 1;
复制
4.查询的列是后面字段的部分时间会走索引查询
Select time1 from table5 where time2 =2017-2;
复制

接下来我们再来说一说联合索引吧?对于联合索引大家应该不陌生,但是使用过程中总觉得并没有使用到联合索引,现在我们就来分析一下其中的原因吧?

alter table tablename index(field1,field2,field3);
复制

以上对表的三个字段,建立了一个联合索引,这种情况下怎样的SQL联合索引才生效:

Where  field1 = 1; 生效
Where field1 = 1 and field2 =2; 生效
Where field1 = 1 and field2 =2 and field3 = 3; 生效
Where field2 = 2; 不生效
Where field3 = 3; 不生效
Where field1 = 1 and field3 = 3; field1生效,field3不生效
Where field1 = 1 and field2 >2 and field3 = 3; field1和field2生效,field3不生效
Where field1 = 1 and field2 like‘pack%and field3 = 3; field1和field2生效,field3不生效

复制

最后我们再来说一说sql语句的优化吧?

1.能使用分页尽量使用分页查询 
2.对分页进行优化
Select * from table1 where order by id limit 2200 10;
改为Select * from table1 where id>2200 order by id limit 10;
这样就可以走id的主键索引了。
3.Not in子查询使用left join查询代替
4.对于or条件查询的可以使用 union all来代替:
Select * from table1 where a =123or b =456;
Select * from table1 where a =123union all Select * from table1 b =456;

复制
PS:防止找不到本篇文章,可以收藏点赞,方便翻阅查找哦。
你的每个点赞和在看,我们都感恩在心


文章转载自编程经验共享,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论