例子如下
问题
需要按总分数排序后,获取某个用户的得分和排名
表名为vt_train_join,表内容如下:
id |
user_id |
total_score |
1 |
2 |
30 |
2 |
5 |
20 |
3 |
3 |
50 |
4 |
6 |
40 |
5 |
1 |
60 |
6 |
4 |
10 |
答案
sql语句如下(查找user_id为47的用户排名和总分):
SELECT rank,sum_score FROM (SELECT *,(@rank\:=@rank+1) AS rank
FROM (SELECT user_id,SUM(total_score) AS sum_score
FROM vt_train_join GROUP BY user_id ORDER BY sum_score DESC) tj,
(SELECT (@rank\:=0)) r) e WHERE user_id=47
注:因为同一个user_id可能有多条数据,所以先对user_id进行了分组