使用子查询进行MYSQL中等查询优化

时间:2013-04-10 13:57:36

标签: mysql optimization query-optimization

我有这个查询返回以下内容:

  • 地区名称
  • 地区ID
  • 此区域的RANK(位置),基于总票数
  • 来自该地区的不同用户的Nb
  • 来自该地区的不同照片

查询需要大约7.5秒才能完成...我想要一些建议来优化我的查询。

            select
            WrappedQuery.*,
            regions.name as region_name,
            regions.id as region_id,
            count(distinct users.id) as nb_users,
            count(distinct photos.id) as nb_photos
            from (
                select
                  @rownum := @rownum +1 as rank,
                  prequery.region_id,
                  prequery.VoteCount
                from
                  ( select @rownum := 0 ) sqlvars,
                  ( select region_id, count(id) VoteCount
                      from votes
                      where theme_id = '{$currentTheme}'
                      group by region_id
                      order by count(id) desc ) prequery
              ) WrappedQuery, regions, users, photos
              WHERE regions.id = WrappedQuery.region_id
              AND users.region_id = WrappedQuery.region_id
              AND photos.region_id = WrappedQuery.region_id
              GROUP BY WrappedQuery.region_id
              ORDER BY WrappedQuery.rank ASC
              LIMIT 0, 1

提前多多感谢。

1 个答案:

答案 0 :(得分:1)

您的查询对您想要实现的目标有太多的开销。我已经为你改写了......

select 
/*you don't need that
@rownum := @rownum +1 as rank, 
*/
regions.name as region_name,
regions.id as region_id,
count(distinct users.id) as nb_users,
count(distinct photos.id) as nb_photos,
count(votes.id) as VoteCount
from votes
INNER JOIN regions ON votes.region_id = regions.id
INNER JOIN users ON users.region_id = regions.id
INNER JOIN photos ON photos.region_id = regions.id
/*you don't need that
, ( select @rownum := 0 ) sqlvars
*/
where theme_id = '{$currentTheme}'
group by regions.id
order by VoteCount DESC
LIMIT 1

我评论了排名的部分,因为你只想要一行。

如果它仍然太慢,则必须发布EXPLAIN SELECT .../*the query from above*/的结果,以便我们可以查看是否使用了索引。同时发布表创建脚本(使用SHOW CREATE TABLE tableName)。要么是这个,要么你自己尝试创建缺失的索引。

<强>更新

再次重写您的查询,可能会更快这样:

select
WrappedQuery.*,
regions.name as region_name,
regions.id as region_id,
count(distinct users.id) as nb_users,
count(distinct photos.id) as nb_photos
from (
       select region_id, count(id) VoteCount
          from votes
          where theme_id = '{$currentTheme}'
          group by region_id
          ORDER BY VoteCount DESC
          LIMIT 1
  ) WrappedQuery, regions, users, photos
  WHERE regions.id = WrappedQuery.region_id
  AND users.region_id = WrappedQuery.region_id
  AND photos.region_id = WrappedQuery.region_id
  GROUP BY WrappedQuery.region_id