繁体   English   中英

通过多个内部联接加速SQL查询

[英]Speed up SQL Query with a multiple inner joins

我有以下查询:

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秒的时间内执行。

如果您需要更多信息来帮助我,请告诉我。

对于此查询(我刚刚重新排列了联接的位置,以便可以更好地关注它们):

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) constant_maps(constant_id, representable_id)aft_people(person_id, lc)aft_offices(id, parent_id) 这些可能有助于加快查询速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM