我的主机说以下查询占用了大量的服务器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
请注意,分析表包含所有综合浏览量和点击次数的记录。所以它非常大。
答案 0 :(得分: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'
答案 1 :(得分: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
和表上的当前索引会很有帮助。