一,普通獲取排序名次
比如獲取一個班級成績排名,分兩步
(1)查出所有用戶和他們的成績排名
select id,maxScore,(@rowNum:=@rowNum+1) as rowNo
from t_user,
(select (@rowNum :=0) ) b
order by t_user.maxScore desc
(2)查出某個用戶在所有用戶成績中的排名
select u.rowNo from (
select id,(@rowNum:=@rowNum+1) as rowNo
from t_user,
(select (@rowNum :=0) ) b
order by t_user.maxScore desc ) u where u.id="2015091810371700001";
二,那假如是統計某個字段總數再排名呢,如場景:
直播間里,觀眾給主播打賞的時候,主播可以收益貨幣,每次打賞都會記錄在A表。
A表:fuid(發起者) uid(收益者) ctime(創建時間戳) coin(貨幣)
現在使用sql語句獲取收益者B的本周收益的排名名次。(不使用循環)
也是分兩步,第一步,將貨幣字段先排序好,再獲取某個單獨用戶的排序名次
(1)獲取統計字段整體排序
select uid,sum(coin) as total,(@rowNum:=@rowNum+1) as rowNo
from money,
(select (@rowNum :=0) ) b
where ctime BETWEEN '1609498844' and '1610103956'
GROUP BY money.uid
order by total desc
(2)獲取排序好的名次字段
select m.rowNo from (select uid,sum(coin) as total,(@rowNum:=@rowNum+1) as rowNo
from money,
(select (@rowNum :=0) ) b
where ctime BETWEEN '1609498844' and '1610103956'
GROUP BY money.uid
order by total desc) m where m.uid =102;
直接上圖:
表數據:
第一次查詢結果:
第二次直接獲取里面的字段就好了