2011-04-08 84 views
0

當我運行一個查詢:我需要索引哪些字段?

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查詢說明,我不明白是什麼意思:

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 |    | 
+----+-------------+--------------+------+-------------------------------------------+---------------+---------+-----------------------+--------+-------------+ 
+0

WAIT ...服務器崩潰了嗎?我懷疑這是一個索引問題。關於你的OP你應該添加索引到categories.id和item_options.item_id – Khez 2011-04-08 11:36:26

+0

你沒錯,它沒有崩潰.... 273行集(3分鐘14.56秒) – user622378 2011-04-08 11:43:45

+0

添加2個索引,然後[優化表](http:///dev.mysql.com/doc/refman/5.1/en/optimize-table.html)。然後告訴我結果^^ – Khez 2011-04-08 11:48:58

回答

1

作爲一個經驗法則,你應該對任何處於joinwheregroup byorder by添加索引部分。

這通常意味着名稱中包含id的所有東西都應該獲得索引。