簡體   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