记同事一次sql 优化(二)

在new_recommend_materials和channel_materials表相同的条件查询,查询时间相差很大,对于你的问题 new_recommend_materials从命名上看是新表,马上想到了可能是表数据碎片的问题。
具体验证如下:
1) 通过系统视图表查看表碎片

localhost.recommend>select table_name,table_rows,concat(round(DATA_LENGTH/1024/1024, 2), 'MB') as size,DATA_FREE  from information_schema.TABLES where table_schema='recommend' order by DATA_LENGTH desc;

记同事一次sql 优化(二)_第1张图片

-rw-rw---- 1 my4515 mysql  69K Nov 29 18:00 channel_materials.frm
-rw-rw---- 1 my4515 mysql 6.0G Jan  9 18:24 channel_materials.ibd
channel_materials表物理大小6G DATA_FREE 表碎片达到2.3G

2) 碎片整理

alter table channel_materials engine=innodb;
localhost.recommend>select table_name,table_rows,concat(round(DATA_LENGTH/1024/1024, 2), 'MB') as size,DATA_FREE  from information_schema.TABLES where table_schema='recommend' order by DATA_LENGTH desc;

记同事一次sql 优化(二)_第2张图片

-rw-rw---- 1 my4515 mysql  69K Jan  9 18:29 channel_materials.frm
-rw-rw---- 1 my4515 mysql 2.5G Jan  9 18:30 channel_materials.ibd

通过碎片整理 物理文件缩小到2.5G

3) 再次验证SQL

SQL>explain select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;
```![这里写图片描述](http://img.blog.csdn.net/20170109193011754?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmpxNWE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

实际查询返回




"se-preview-section-delimiter">

SQL>select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;
10 rows in set (2.53 sec)
“`
碎片整理后 查询返回从5min减少3秒,虽然已经大幅降低 但还是慢 说明status的选择性不好,按之前force_index(index_current_check_time)秒内返回

添加联合索引
SQL>alter table channel_materials add index inx_status_time on (status,current_check_time);
SQL>explain select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;

SQL>select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;
10 rows in set (2.53 sec)

碎片整理后 查询返回从5min减少3秒,虽然已经大幅降低 但还是慢 说明status的选择性不好,按之前force_index(index_current_check_time)秒内返回

添加联合索引


SQL>alter table channel_materials add index inx_status_time on (status,current_check_time);
SQL>explain select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;
这里写图片描述

实际查询

SQL>select mblog_info from channel_materials where (status = 7788) and current_check_time >= 1483816341 and current_check_time <= 1483926441 limit 10;
10 rows in set (0.00 sec)

So 造成2个表查询相差较大 是表碎边问题, 对于该SQL查询 还是之前建议 删除status索引 或 添加联合索引(status,current_check_time)。

你可能感兴趣的:(sql-优化,优化,sql)