2012-02-02 66 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