mysql 单表索引优化案例
来源:互联网 发布:白鹿原小说败笔 知乎 编辑:程序博客网 时间:2024/06/05 04:42
#查询category_id为1且comments大于1 的情况下,views最多的article_id(article 表只有主键id索引)
EXPLAN SELECT id ,author_id FROM article WHERE category_id=1 AND comments>1 ORDER BY views DESC LIMIT 1;
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+
| 1 | SIMPLE | article | ALL | NULL | NULL | NULL | NULL | 6 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
#结论:type为ALL,Extra存在Using filesort,情况较坏,需要优化
1、加索引
CREATE INDEX idx_article_ccv ON article(category_id,comments,views);
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+
| 1 | SIMPLE | article | range | idx_article_ccv |idx_article_ccv | 8| NULL | 6 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
#依然存在Using filesort
#原因:因为按照BTree索引的工作原理,
#先排序category_id,
#如果category_id相同,再排序comments,如果comments相同,则排序views。
#当comments字段在联合索引里处于中间位置时,
#因为comments>1条件是一个范围值,
#mysql无法利用索引再对后边的views部分进行检索,即range类型查询字段后面的索引失效。
2、删除1中索引,增加新的索引
DROP INDEX idx_article_ccv ON article;
CREATE INDEX idx_article_cv ON article(category_id,views);
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+
| 1 | SIMPLE | article | ref| idx_article_cv | idx_article_cv | 4 |const | 2 | Using where|
+----+-------------+-------+------+---------------+------+---------+------+------+-------+------+-------+------+-------+------+
- mysql 单表索引优化案例
- MySQL的索引单表优化案例分析
- 索引案例一:单表优化案例
- mysql 两个表索引优化案例
- mysql 三个表索引优化案例
- mysql 索引优化案例(索引失效)
- Mysql性能优化案例-覆盖索引分享
- Mysql性能优化案例研究 - 覆盖索引和SQL_NO_CACHE
- mysql索引测试案例
- MySql优化--索引优化
- 「mysql优化专题」单表查询优化的一些小总结,非索引设计(3)
- MySQL SQL 优化案例:JOIN派生表
- mysql优化案例分析
- mysql 查询优化案例
- mysql 数据库优化案例
- MYSQL优化案例
- MySQL优化案例
- Mysql性能优化案例
- ShowModal和Show的区别
- [PHP] 网页验证码的实现
- 设置文本与图片的对其方式,元素的隐藏
- 递归及尾递归优化
- MySql基于GTID主从复制的搭建
- mysql 单表索引优化案例
- Eclipse:启用代码自动补全功能
- 分拆素数和
- 文档编写
- 进程控制 (二) & Others
- Java中static关键字的五种用法详解(含代码举例)
- getWriter() has already been called for this response
- UVA
- MySQL中常见的字符串处理函数