MySQL Query很慢(加入/计数)

时间:2015-03-25 19:46:39

标签: mysql performance myisam

我有这个问题:

 SELECT `assemblies`.`id`,
   `assemblies`.`type`,
   `assemblies`.`champion`,
   `assemblies`.`name`,
   `assemblies`.`author`,
   `assemblies`.`githublastmod`,
   ( assemblies.forum IS NOT NULL ) AS forumExists,
   Count(votes.id)                  AS votesCount,
   Count(install_clicks.id)         AS installCount,
   Count(github_clicks.id)          AS githubCount,
   Count(forum_clicks.id)           AS forumCount
FROM   `assemblies`
   INNER JOIN `votes`
           ON `votes`.`assembly` = `assemblies`.`id`
   INNER JOIN `install_clicks`
           ON `install_clicks`.`assembly` = `assemblies`.`id`
   INNER JOIN `github_clicks`
           ON `github_clicks`.`assembly` = `assemblies`.`id`
   INNER JOIN `forum_clicks`
           ON `forum_clicks`.`assembly` = `assemblies`.`id`
WHERE  `assemblies`.`type` = 'utility'
   AND Unix_timestamp(Date(assemblies.githublastmod)) > '1419536536'
GROUP  BY `assemblies`.`id`
ORDER  BY `votescount` DESC,
      `githublastmod` DESC  

由于某种原因,这个查询非常慢,我正在使用数据库引擎MyISAM。我希望有人可以帮助我:)

解释命令: enter image description here

2 个答案:

答案 0 :(得分:1)

您的问题应该使用正确的索引来解决:

CREATE INDEX index_name_1 ON `votes`(`assembly`);
CREATE INDEX index_name_2 ON `install_clicks`(`assembly`);
CREATE INDEX index_name_3 ON `github_clicks`(`assembly`);
CREATE INDEX index_name_4 ON `forum_clicks`(`assembly`);

创建这些索引后再次尝试查询,它应该更快。

答案 1 :(得分:1)

我相信这是一种情况,使得计数的子查询将使它运行得更快(并且值将是正确的)。

原始查询的问题是中间行数量激增:对于每个'程序集',有n1票,n2个安装等。这导致n1 * n2 * ... rows per 装配。

SELECT  `assemblies`.`id`, `assemblies`.`type`, `assemblies`.`champion`,
        `assemblies`.`name`, `assemblies`.`author`, `assemblies`.`githublastmod`,
        ( assemblies.forum IS NOT NULL ) AS forumExists, 
      ( SELECT  Count(*)
            FROM  votes
            WHERE  `assembly` = `assemblies`.`id` 
      ) AS votesCount, 
      ( SELECT  Count(*)
            FROM  install_clicks
            WHERE  `assembly` = `assemblies`.`id` 
      ) AS installCount, 
      ( SELECT  Count(*)
            FROM  github_clicks
            WHERE  `assembly` = `assemblies`.`id` 
      ) AS githubCount, 
      ( SELECT  Count(*)
            FROM  forum_clicks.id
            WHERE  `assembly` = `assemblies`.`id` 
      ) AS forumCount
    FROM  `assemblies`
    WHERE  `assemblies`.`type` = 'utility'
      AND  Unix_timestamp(Date(assemblies.githublastmod)) > '1419536536'
    ORDER BY  `votescount` DESC, `githublastmod` DESC 

每个辅助表都需要一个INDEX assembly开始