MySQL查询没有利用索引

时间:2010-06-21 08:55:25

标签: mysql optimization indexing

我正在分析查询(处理名为nextgen gallery的wordpress插件),这就是我得到的

查询:

EXPLAIN
      SELECT title, filename 
        FROM wp_ngg_pictures wnp 
   LEFT JOIN wp_ngg_gallery wng 
          ON wng.gid = wnp.galleryid 
    GROUP BY wnp.galleryid 
       LIMIT 5

结果:

+----+-------------+-------+--------+---------------+---------+---------+-----------------------+------+---------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                   | rows | Extra                           |
+----+-------------+-------+--------+---------------+---------+---------+-----------------------+------+---------------------------------+
|  1 | SIMPLE      | wnp   | ALL    | NULL          | NULL    | NULL    | NULL                  |  439 | Using temporary; Using filesort | 
|  1 | SIMPLE      | wng   | eq_ref | PRIMARY       | PRIMARY | 8       | web1db1.wnp.galleryid |    1 |                                 | 
+----+-------------+-------+--------+---------------+---------+---------+-----------------------+------+---------------------------------+

所以我这样做:

ALTER TABLE wp_ngg_pictures ADD INDEX(galleryid);

在我的本地测试系统中,我得到了:

+----+-------------+-------+--------+---------------+-----------+---------+--------------------+------+-------+
| id | select_type | table | type   | possible_keys | key       | key_len | ref                | rows | Extra |
+----+-------------+-------+--------+---------------+-----------+---------+--------------------+------+-------+
|  1 | SIMPLE      | wnp   | index  | galleryid     | galleryid | 8       | NULL               |   30 |       |
|  1 | SIMPLE      | wng   | eq_ref | PRIMARY       | PRIMARY   | 8       | test.wnp.galleryid |    1 |       |
+----+-------------+-------+--------+---------------+-----------+---------+--------------------+------+-------+

看起来很好,但在最后的服务器上我得到了

+----+-------------+-------+--------+---------------+-----------+---------+-----------------------+------+-------+
| id | select_type | table | type   | possible_keys | key       | key_len | ref                   | rows | Extra |
+----+-------------+-------+--------+---------------+-----------+---------+-----------------------+------+-------+
|  1 | SIMPLE      | wnp   | index  | galleryid     | galleryid | 8       | NULL                  |  439 |       | 
|  1 | SIMPLE      | wng   | eq_ref | PRIMARY       | PRIMARY   | 8       | web1db1.wnp.galleryid |    1 |       | 
+----+-------------+-------+--------+---------------+-----------+---------+-----------------------+------+-------+

所以使用了索引但是仍然扫描了所有行?为什么会这样?

我唯一能看到的是mysql版本,即5.1.47(本地)与5.0.45(远程),两个系统的数据相同。

1 个答案:

答案 0 :(得分:0)

EXPLAIN SELECT输出中的 rows 列是对MySQL认为必须检查以执行查询的行数的估计,所以我猜你的本地版本可能是有的(5.1。 47)估计比你的远程版本更好。

如果没有EXPLAIN子句,两个查询都会生成相同的输出吗?如果您更改查询以使用STRAIGHT_JOIN会发生什么?