1. 复合索引不要跨列或无序使用(最佳左前缀原则)
复合索引尽量使用全索引匹配
2. 复合索引不能使用 不等于(!= <>)、IS NUL(IS NOT NULL) 或 大于号(>) 否则会造成自身以及右侧索引全部失效
| explain select * from book where authorid = 1 and typeid =2 ; |
| |
| |
| |
| explain select * from book where authorid != 1 and typeid =2 ; |
| explain select * from book where authorid != 1 and typeid !=2 ; |
| |
| |
| 体验概率情况(< > =):原因是服务层中有SQL优化器,可能会影响我们的优化。 |
| drop index idx_typeid on book; |
| drop index idx_authroid on book; |
| alter table book add index idx_book_at (authorid,typeid); |
| explain select * from book where authorid = 1 and typeid =2 ; |
| explain select * from book where authorid > 1 and typeid =2 ; |
| explain select * from book where authorid = 1 and typeid >2 ; |
| |
| explain select * from book where authorid < 1 and typeid =2 ; |
| explain select * from book where authorid < 4 and typeid =2 ; |
| |
| |
| |
3. 不要在索引上进行任何操作(函数、计算以及类型转换),否则索引失效
| 假设A.X是索引 |
| |
| SELECT ... WHERE A.X*3 = ... 【无效】 |
| select ..where A.x = .. ; |
| 不要:select ..where A.x*3 = .. ; |
| explain select * from book where authorid = 1 and typeid = 2 ; |
| explain select * from book where authorid = 1 and typeid*2 = 2 ; |
| explain select * from book where authorid*2 = 1 and typeid*2 = 2 ; |
| explain select * from book where authorid*2 = 1 and typeid = 2 ; |
| |
| drop index idx_atb on book ; |
| alter table book add index idx_authroid (authorid) ; |
| alter table book add index idx_typeid (typeid) ; |
| explain select * from book where authorid*2 = 1 and typeid = 2 ; |
4. LIKE尽可能以"常量"开头,不要以"%"开头,否则索引失效
| select * from xx where name like '%x%' ; |
| |
| explain select * from teacher where tname like '%x%'; |
| |
| explain select * from teacher where tname like 'x%'; |
| |
| explain select tname from teacher where tname like '%x%'; |
5. 尽量不要使用or,否则索引失效
| explain select * from teacher where tname ='' or tcid >1 ; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具