作者:王丹__-划_402 | 来源:互联网 | 2023-10-12 09:12
索引的使用
索引是数据库优化最常用也是最重要的手段之一,
通过索引通常可以帮助用户解决大多数的MySQL的性能优化问题
验证索引提升查询效率
![](https://img0.php1.cn/3cdc5/6e5e/42f/1b713b06aee8ba54.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/d7190aec423678f0.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/afae66d2ad7ef490.png)
查询速度很快,接近0s ,主要的原因是因为id为主键,有索引;
验证索引提升查询效率
![](https://img0.php1.cn/3cdc5/6e5e/42f/2323b6effe8c8e70.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/8585c5d23d1bd176.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/f48e798df3dbc008.png)
索引的使用
准备环境
![](https://img0.php1.cn/3cdc5/6e5e/42f/1f07bb4a535cf547.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/d11cb2ab557bb542.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/e0e71fa7ab8ce1a4.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/9547b100bf69b549.png)
避免索引失效
1). 全值匹配,对索引中所有列都指定具体值。索引生效,执行效率高。
![](https://img0.php1.cn/3cdc5/6e5e/42f/7c968086b29eda79.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/1bcb323f74bf7d3d.png)
2). 最左前缀法则
如果索引了多列,要遵守最左前缀法则。
指的是查询从索引的最左前列开始,并且不跳过索引中的列。
匹配最左前缀法则,走索引:
![](https://img0.php1.cn/3cdc5/6e5e/42f/1d5017ac8f9c993f.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/d817b00b1cd5aa85.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/74bf652f7a9a5107.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/82ae35bae5660aa3.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/fa2d90571d2436ef.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/f9ebcafe1ef84ccc.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/27977714a6d9e6ad.png)
3). 范围查询右边的列,不能使用索引。
![](https://img0.php1.cn/3cdc5/6e5e/42f/8f14d7ce0a8287df.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/d26eccc081f1e9ca.png)
根据前面的两个字段name , status 查询是走索引的,但是最后一个条件address 没有用到索引。
4). 不要在索引列上进行运算操作,索引将失效。
![](https://img0.php1.cn/3cdc5/6e5e/42f/08942bf7499398a7.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/4be8d03c521212d6.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/51bc3dea05acdf60.png)
5). 字符串不加单引号,造成索引失效。
![](https://img0.php1.cn/3cdc5/6e5e/42f/8806e12bf3d7ac95.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/d6bfed0c3ca9a685.png)
![](https://img0.php1.cn/3cdc5/6e5e/42f/3169a424dd111758.png)