0

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

  • 地区名称
  • 区域编号
  • 该区域的排名(位置),基于总票数
  • Nb 来自该地区的不同用户
  • 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

提前非常感谢。

4

1 回答 1

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

我用排名注释掉了部分,因为无论如何你只想要 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
于 2013-04-10T14:15:28.680 回答