mysql - 使用多个内连接加速 SQL 查询

标签 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 秒内执行此查询。

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

最佳答案

对于这个查询(我刚刚重新排列了连接,以便我可以更好地跟踪它们):

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) 。这些可能有助于加快查询速度。

关于mysql - 使用多个内连接加速 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29431203/

相关文章:

mysql - 使用 concat() 和cast() 按月和年列排序

SQL WHERE条件为列表,列类型为数组

c# - 找不到对象 "dbo.Table",因为它不存在或您没有权限

sql - 是否有 postgres 命令来列出/删除所有物化 View ?

Mysql用户定义变量为0时不更新

mysql - 将 MySQL 函数的结果(在 WHERE 中使用)保留在我的查询结果中

mysql表问题

sql - 如何从一个 cfc 文件中的函数查询中调用另一个 CFC 文件中的函数?

mysql - 我的 SQL 错误 #1015 - 无法锁定文件 (errno : 165 - Table is read only) innodb engine only

mysql - 如何从 mysql 数据库创建 json 文件?