使用多个内部联接加速SQL查询

时间:2015-04-03 11:18:42

标签: mysql 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有大约5M条记录。

字段有索引
  • aft_people.person_id
  • aft_constant_maps.representable_id
  • aft_constant_maps.constant_id

查询真的很慢,有时根本不加载。我需要在不到10秒的时间内执行此查询。

如果您想了解更多信息,请与我联系。

1 个答案:

答案 0 :(得分: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)。这些可能有助于加快查询速度。

相关问题