2015-04-03 26 views
0

我有以下查詢:加快SQL查詢與多個內部連接

SELECT COUNT(DISTINCT(`person_id`)) as `count`, `mc_office`.`name` as `office_name` 
FROM `aft_people` 
         INNER JOIN `aft_offices` 
         ON `aft_people`.`lc`=`aft_offices`.`id` 
         INNER JOIN `aft_offices` as `mc_office` 
         ON `aft_offices`.`parent_id` = `mc_office`.`id` 
         INNER JOIN `aft_constant_maps` as `constant_maps` 
         ON `aft_people`.`person_id` = `constant_maps`.`representable_id` 
         WHERE `constant_maps`.`constant_id` IN (741) 
         GROUP BY `mc_office`.`name` 

表aft_people具有1M記錄和aft_constant_maps有500萬左右的記錄。 有索引的字段

  • aft_people.person_id
  • aft_constant_maps.representable_id
  • aft_constant_maps.constant_id

查詢是真的很慢,有時甚至不加載所有。我需要這個查詢在不到10秒的時間內執行。

請讓我知道你是否想要更多的信息來幫助我。

+1

顯示解釋計劃'解釋選擇...' – 2015-04-03 11:19:22

回答

0

對於此查詢(我剛剛重新排列聯接的,所以我可以更好地跟隨他們):

SELECT COUNT(DISTINCT(`person_id`)) as `count`, 
     `mc_office`.`name` as `office_name` 
from `aft_people` INNER JOIN 
    `aft_constant_maps` as `constant_maps` 
    ON `aft_people`.`person_id` = `constant_maps`.`representable_id` INNER JOIN 
    `aft_offices` 
    ON `aft_people`.`lc` = `aft_offices`.`id` INNER JOIN 
    `aft_offices` as `mc_office` 
    ON `aft_offices`.`parent_id` = `mc_office`.`id` 
WHERE `constant_maps`.`constant_id` IN (741) 
GROUP BY `mc_office`.`name` 

最好的指標爲:constant_maps(constant_id, representable_id)aft_people(person_id, lc)aft_offices(id, parent_id)。這可能有助於加快查詢速度。