2012-02-02 62 views
1

当它应该使用(faver_profile_id,已移除,id)上的索引时,Mysql正在使用(faver_profile_id,已移除,notice_id)上的索引。奇怪的是,对于faver_profile_id的某些值,它确实使用了正确的索引。我可以使用FORCE INDEX,这极大地加快了查询速度,但我想知道为什么mysql正在这样做。为什么Mysql使用错误的索引?

这是一个使用INSERT INTO .. SELECT FROM从另一个表复制的新表(35m行)。 之后我没有运行OPTIMIZE TABLE或ANALYZE。可以帮助吗?

SELECT `Item`.`id` , `Item`.`cached_image` , `Item`.`submitter_id` , `Item`.`source_title` , `Item`.`source_url` , `Item`.`source_image` , `Item`.`nudity` , `Item`.`tags` , `Item`.`width` , `Item`.`height` , `Item`.`tumblr_id` , `Item`.`tumblr_reblog_key` , `Item`.`fave_count` , `Item`.`file_size` , `Item`.`animated` , `Favorite`.`id` , `Favorite`.`created` 
FROM `favorites` AS `Favorite` 
LEFT JOIN `items` AS `Item` ON ( `Favorite`.`notice_id` = `Item`.`id`) 
WHERE `faver_profile_id` =11619 
AND `Favorite`.`removed` =0 
AND `Item`.`removed` =0 
AND `nudity` =0 
ORDER BY `Favorite`.`id` DESC 
LIMIT 26 

查询执行计划: “idx_notice_id_profile_id” 是(faver_profile_id,删除,notice_id)

1 | SIMPLE  | Favorite | ref | idx_faver_idx_id,idx_notice_id_profile_id,notice_id_idx | idx_notice_id_profile_id | 4  | const,const       | 15742 | Using where; Using filesort | 
1 | SIMPLE  | Item  | eq_ref | PRIMARY             | PRIMARY     | 4  | gragland_imgfave.Favorite.notice_id |  1 | Using where  
+0

应该高度@ajreal上面还好添加的执行计划 – ajreal 2012-02-02 18:05:24

+0

。 – makeee 2012-02-02 18:13:58

回答

0

索引我不知道,如果它造成任何混乱或没有,但也许通过将一些AND限定符移动到Item的连接可能会有所帮助,因为它与ITEM直接相关,而不是最喜欢的。另外,我已经明确地限定了table.field引用,否则它们会丢失。

SELECT 
     Item.id, 
     Item.cached_image, 
     Item.submitter_id, 
     Item.source_title, 
     Item.source_url, 
     Item.source_image, 
     Item.nudity, 
     Item.tags, 
     Item.width, 
     Item.height, 
     Item.tumblr_id, 
     Item.tumblr_reblog_key, 
     Item.fave_count, 
     Item.file_size, 
     Item.animated, 
     Favorite.id, 
     Favorite.created 
    FROM favorites AS Favorite 
    LEFT JOIN items AS Item 
     ON Favorite.notice_id = Item.id 
     AND Item.Removed = 0 
     AND Item.Nudity = 0 
    WHERE Favorite.faver_profile_id = 11619 
    AND Favorite.removed = 0 
    ORDER BY Favorite.id DESC 
    LIMIT 26 

所以,现在,从“收藏夹”表,它的标准是明确下来faver_profile_id,删除,ID(订单)

+0

尝试了您的建议,但仍不幸地使用了错误的索引。 – makeee 2012-02-03 21:07:45