mysql 慢查询处理

发布时间 2023-07-08 10:51:33作者: djiz

mysql 执行

EXPLAIN SELECT `post`.*,`category_post`.`category_id` FROM `mj_portal_post` `post` INNER JOIN `mj_portal_category_post` `category_post` ON `post`.`id`=`category_post`.`post_id` WHERE `post`.`post_status` = 1 AND `post`.`post_type` = 1 AND `post`.`delete_time` = 0 AND `category_post`.`category_id` IN ('1',2,3,4) AND `post`.`create_time` >= 0 ORDER BY post.published_time DESC LIMIT 9180,20

结果

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra  
1 SIMPLE category_post ALL term_taxonomy_id NULL NULL NULL 23041 Using where; Using temporary; Using filesort
1 SIMPLE post eq_ref PRIMARY,type_status_date,post_date PRIMARY 8 数据库.category_post.post_id 1 Using where

type ALL 遍历了全表,而且数据量很大,这应该是造成慢查询的主要原因

type eq_ref  唯一性索引扫描,表中只有一条记录与之匹配。一般是两表关联,关联条件中的字段是主键或唯一索引。关联字段确实是主键 post.id 

post 没法优化了,看看portal_category_post 怎么优化

Extra列

      Using temporary:使用了临时表保存中间结果。常见于排序order by和分组查询group by(最好优化)

      Using filesort:使用外部的索引排序,而不是按照表内的索引顺序进行读取。(一般需要优化)

key 列: NULL 没有使用索引

ref 列:Null  哪些列或常量被用于查找索引列上的值,因为没有使用索引,所以是null

 

参考 :mysql中explain详解 (type 取值及解释)  链接: https://www.jianshu.com/p/be1c86303c80

           mysql 索引优化   https://www.cnblogs.com/istitches/p/17153172.html