索引需要哪些字段?

时间:2011-04-08 11:33:43

标签: mysql

当我运行查询时:

select categories.name as CatName, items.name as ItemName, item_options.price as Price from categories
left join items on categories.id = items.category_id
left join item_options on items.id = item_options.item_id
Where categories.takeawayID = 55276

获得结果需要很长时间:273行(3分14.56秒)

看起来我需要在字段上添加索引?但是哪一个?

我尝试使用SELECT查询添加EXPLAIN,我不明白它的含义:

mysql> Explain select categories.name as CatName, items.name as ItemName, item_options.price as Price from categories
    -> left join items on categories.id = items.category_id
    -> left join item_options on items.id = item_options.item_id
    -> Where categories.takeawayID = 55276;
+----+-------------+--------------+------+-------------------------------------------+---------------+---------+-----------------------+--------+-------------+
| id | select_type | table        | type | possible_keys                             | key           | key_len | ref                   | rows   | Extra       |
+----+-------------+--------------+------+-------------------------------------------+---------------+---------+-----------------------+--------+-------------+
|  1 | SIMPLE      | categories   | ALL  | NULL                                      | NULL          | NULL    | NULL                  |  14086 | Using where |
|  1 | SIMPLE      | items        | ref  | category_id_2,category_id_3,category_id_4 | category_id_2 | 4       | menu.categories.id    |      9 |             |
|  1 | SIMPLE      | item_options | ALL  | NULL                                      | NULL          | NULL    | NULL                  | 197401 |             |
+----+-------------+--------------+------+-------------------------------------------+---------------+---------+-----------------------+--------+-------------+

1 个答案:

答案 0 :(得分:1)

根据经验,您应该为joinwheregroup byorder by部分中的任何内容添加索引。

这通常意味着名称中id的所有内容都应该获得索引。