0

我的主机说以下查询占用了大量服务器 CPU。请告诉我如何优化它。

SELECT COUNT(*) FROM (SELECT COUNT(*) AS tot,wallpapers.*,resolutions.res_height,resolutions.res_width FROM wallpapers

INNER JOIN analytics ON analytics.`wall_id` = wallpapers.`wall_id`

INNER JOIN resolutions ON resolutions.`res_id` = wallpapers.`res_id`



WHERE analytics.ana_date >= '2013-09-01 16:36:56' AND wallpapers.wall_status = 'public'

GROUP BY analytics.`wall_id`) as Q 

请注意,分析表包含所有浏览量和点击量的记录。所以它非常非常大。

4

2 回答 2

1

据我所知,您的查询只是wall_id在通过连接和WHERE子句过滤后计算不同的值。这样的事情应该很接近:

SELECT COUNT(DISTINCT analytics.wall_id)
FROM wallpapers
INNER JOIN analytics ON analytics.wall_id = wallpapers.wall_id
INNER JOIN resolutions ON resolutions.res_id = wallpapers.res_id
WHERE analytics.ana_date >= '2013-09-01 16:36:56'
  AND wallpapers.wall_status = 'public'
于 2013-09-03T15:32:28.560 回答
0

这是您的查询:

SELECT COUNT(*)
FROM (SELECT COUNT(*) AS tot, wallpapers.*, resolutions.res_height, resolutions.res_width
      FROM wallpapers INNER JOIN
           analytics
           ON analytics.`wall_id` = wallpapers.`wall_id` INNER JOIN
           resolutions
           ON resolutions.`res_id` = wallpapers.`res_id`
      WHERE analytics.ana_date >= '2013-09-01 16:36:56' AND
            wallpapers.wall_status = 'public'
      GROUP BY analytics.`wall_id`
) as Q 

子查询和group by. 您可以将其替换为:

SELECT COUNT(distinct analytics.wall_id)
FROM wallpapers INNER JOIN
     analytics
     ON analytics.`wall_id` = wallpapers.`wall_id` INNER JOIN
     resolutions
     ON resolutions.`res_id` = wallpapers.`res_id`
WHERE analytics.ana_date >= '2013-09-01 16:36:56' AND
      wallpapers.wall_status = 'public';

然后,您可能能够使用索引进行进一步优化,但查看explain此查询的一个和表上的当前索引会很有帮助。

于 2013-09-03T15:34:01.523 回答