是一个积分明细表,表结构如下:id    user_id    type    score
1     12         1       13
2     16         2       24
3     12         2       53
4     22         1       32
5     14         1       17
6     32         2       43
7     22         2       34
...一个用户有多条积分明细记录。需要求出用户的总积分排行。
我写的SQL如下:
select user_id, sum(score) as total_score from tablename
group by user_id order by total_score desc这样写可以实现功能,但是当表数据量很大的时候(几百万条),查询起来变得非常慢!
请教在不增加表的情况下如何优化这个SQL实现同样的功能,谢谢。

解决方案 »

  1.   

    select user_id, sum(score) as total_score 
    from tablename
    group by user_id 
    order by total_score desc这个查询,没有什么好办法。唯一能做的就是添加 (user_id,score) 的索引。
    但无法避免全表扫描
      

  2.   

    新建立个字段 total
    你可以更改表该字段的结构 是自动排序的
      

  3.   

    我觉得应该是对 (user_id) 做索引吧?
    做 (user_id,score) 的索引能有用吗?
      

  4.   

    添加了(user_id,score) 索引,查询由10多秒变成6秒,不错
      

  5.   

    感谢 ACMAIN_CHM 的指点,通过学习,现在终于知道 (user_id,score) 这个索引的妙处了!  :D