MySQL Explain 的行数与慢查询日志不同

Posted

技术标签:

【中文标题】MySQL Explain 的行数与慢查询日志不同【英文标题】:MySQL Explain has different row count than slow query log 【发布时间】:2014-08-08 15:49:05 【问题描述】:

我在慢查询日志中有这个条目:

# User@Host: user[host] @  [ip]
# Thread_id: 1514428  Schema: db  Last_errno: 0  Killed: 0
# Query_time: 2.795454  Lock_time: 0.000116  Rows_sent: 15  Rows_examined: 65207  Rows_affected: 0  Rows_read: 65207
# Bytsent: 26618
SET timestamp=1407511874;
select off.*,translated_title,translated_description
from products off  USE INDEX(id_viewed)
INNER JOIN members mem ON off.uid = mem.id
Left Join product_language_new pol ON off.id = pol.offer_id and pol.language='en'
where off.approved=1
order by off.viewed
LIMIT 15; 

当我解释这个查询时,绝对没问题。

mysql> explain select off.*,translated_title,translated_description
from products off  USE INDEX(id_viewed)
INNER JOIN members mem ON off.uid = mem.id
Left Join product_language_new pol ON off.id = pol.offer_id and pol.language='en'
where off.approved=1
order by off.viewed
LIMIT 15;

+----+-------------+-------+--------+-------------------------+-------------+---------+---------------------------+------+-------------+
| id | select_type | table | type   | possible_keys           | key         | key_len | ref                       | rows | Extra       |
+----+-------------+-------+--------+-------------------------+-------------+---------+---------------------------+------+-------------+
|  1 | SIMPLE      | off   | index  | NULL                    | id_viewed   | 4       | NULL                      |    3 | Using where |
|  1 | SIMPLE      | mem   | eq_ref | PRIMARY                 | PRIMARY     | 4       | db.off.uid                |    1 | Using index |
|  1 | SIMPLE      | pol   | ref    | offer_id,id_language    | offer_id    | 5       | db.off.id                 |    4 |             |
+----+-------------+-------+--------+-------------------------+-------------+---------+---------------------------+------+-------------+
3 rows in set (0.17 sec)

如何优化此查询?为什么解释显示 3 行,慢查询日志说它检查了 65207 行。

是的,我尝试了 FORCE INDEX,没有强制索引,但它只会变得更糟。

【问题讨论】:

为所有表添加create table语句 【参考方案1】:

看起来查询不能使用id_viewed,因为它不在possible_keys 列中,而extra 列只是说Using where

我还猜测rows 指的是您拥有LIMITed 的返回行,而不是它必须扫描的行数。您可以删除LIMITEXPLAIN

我会在(id, approved) 上尝试一个复合索引,并可能在(viewed) 上尝试一个单一索引来进行排序。

【讨论】:

以上是关于MySQL Explain 的行数与慢查询日志不同的主要内容,如果未能解决你的问题,请参考以下文章

MySQL - - 索引原理与慢查询优化

MySQL六:索引原理与慢查询优化

MySQL之索引原理与慢查询优化

mysql五:索引原理与慢查询优化

Navicat:显示的行数与表中实际的行数不一致

Navicat:显示的行数与表中实际的行数不一致