简体   繁体   中英

Speed up SQL Query with a multiple inner joins

I have the following query :

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`

Table aft_people has 1M records and aft_constant_maps has around 5M records. There are indexes on the fields

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

The query is really really slow and sometimes it doesn't even load at all. I need this query to execute in less than 10 seconds.

Do let me know if you would like more information to help me out.

For this query (I've just rearranged the join's so I can follow them better):

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`

The best indexes are: constant_maps(constant_id, representable_id) , aft_people(person_id, lc) , and aft_offices(id, parent_id) . These might help speed up the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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