2010-06-23 166 views
3
Background: 
entities tables currently has 14,111 records 
articles table currently has 5211 records 

我想找到是有效的(完成)的所有文章,並有實體「谷歌」爲什麼我的MySQL查詢很慢?

# Finding articles that have the entity google takes: 
# 4 ms 
SELECT `Article`.`id` FROM `articles_entities` AS `ArticlesEntity` 
LEFT JOIN `entities` AS `Entity` ON (`ArticlesEntity`.`entity_id` = `Entity`.`id`) 
WHERE `Entity`.`strict` = 'google' 

# Finding articles that have the entity google and is active takes: 
# 1800 ms 
SELECT `Article`.`id` FROM `articles_entities` AS `ArticlesEntity` 
LEFT JOIN `entities` AS `Entity` ON (`ArticlesEntity`.`entity_id` = `Entity`.`id`) 
LEFT JOIN `articles` AS `Article` ON (`ArticlesEntity`.`article_id` = `Article`.`id`) 
WHERE `Entity`.`strict` = 'google' AND `Article`.`state` = 'completed' 

什麼可能是與查詢需要如此長的問題?

我想補充一點,數據透視表中的兩個字段都是索引的。

在此先感謝您的幫助

UPDATE

id select_type table type possible_keys key key_len ref rows Extra 
1 SIMPLE Entity ref PRIMARY,strict strict 767 const 1 Using where 
1 SIMPLE ArticlesEntity ref article_id,entity_id,article_id_2 entity_id 108 b2b.Entity.id 4 
1 SIMPLE Article eq_ref PRIMARY,state PRIMARY 108 b2b.ArticlesEntity.article_id 1 Using where 
+0

查詢返回多少行? – dkretz 2010-06-23 17:52:06

回答

1

Entity.strict或Article.state不被索引。 在您的SELECT語句之前使用EXPLAIN並檢查哪些表正在被完全掃描。這將暗示需要編制索引的內容。

+0

兩者都編入索引 – Lizard 2010-06-23 13:01:39

+2

你在每張桌上都有哪些索引,EXPLAIN告訴你什麼? – 2010-06-23 13:03:03

+0

查看底部opf問題的更新 – Lizard 2010-06-23 13:08:49

1

你真的需要左連接嗎?!恕我直言,你的查詢應該得到一個提升沒有它;)