今天我们来说一说索引优化。首先我们来说一说什么情况需要建立索引吧?
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;
复制
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 = ‘123’ or b = ‘456’;
Select * from table1 where a = ‘123’ union all Select * from table1 b = ‘456’;复制


文章转载自编程经验共享,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
【专家有话说第五期】在不同年龄段,DBA应该怎样规划自己的职业发展?
墨天轮编辑部
1270次阅读
2025-03-13 11:40:53
【专家观点】罗敏:从理论到真实SQL,感受DeepSeek如何做性能优化
墨天轮编辑部
1269次阅读
2025-03-06 16:45:38
MySQL8.0统计信息总结
闫建(Rock Yan)
482次阅读
2025-03-17 16:04:03
2月“墨力原创作者计划”获奖名单公布
墨天轮编辑部
453次阅读
2025-03-13 14:38:19
Ogg23ai高手必看-MySQL Innodb Cluster跟oracle的亲密接触
曹海峰
446次阅读
2025-03-04 21:56:13
SQL优化 - explain查看SQL执行计划(一)
金同学
387次阅读
2025-03-13 16:04:22
SQLE 4.0 正式版发布,新增 SQL 重写、SQL 性能追踪、语法知识图谱等功能
爱可生开源社区
354次阅读
2025-03-07 10:30:00
MySQL突然崩溃?教你用gdb解剖core文件,快速锁定“元凶”!
szrsu
333次阅读
2025-03-13 00:29:43
MySQL生产实战优化(利用Index skip scan优化性能提升257倍)
chengang
325次阅读
2025-03-17 10:36:40
一键装库脚本3分钟极速部署,传统耗时砍掉95%!
IT邦德
232次阅读
2025-03-10 07:58:44