您好,登錄后才能下訂單哦!
這篇文章主要介紹了MYSQL如何實現排名及查詢指定用戶排名功能,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
表結構:
CREATE TABLE test.testsort ( id int(11) NOT NULL AUTO_INCREMENT, uid int(11) DEFAULT 0 COMMENT '用戶id', score decimal(10, 2) DEFAULT 0.00 COMMENT '分數', PRIMARY KEY (id) ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = '測試排序' ROW_FORMAT = DYNAMIC;
思路:可以先排序,再對結果進行編號;也可以先查詢結果,再排序編號。
說明:
@rownum := @rownum + 1 中 := 是賦值的作用,這句話的意思是先執行@rownum + 1,然后把值賦給@rownum;
(SELECT @rownum := 0) r 這句話的意思是設置rownum字段的初始值為0,即編號從1開始。
實現排名:
方法一:
SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, (SELECT * FROM testsort ORDER BY score DESC) AS t;
方法二:
SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, testsort AS t ORDER BY t.score DESC;
結果:
查看指定用戶排名:
方法一:
SELECT b.* FROM ( SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, (SELECT * FROM testsort ORDER BY score DESC) AS t ) AS b WHERE b.uid = 222;
方法二:
SELECT b.* from ( SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r, testsort AS t ORDER BY t.score DESC ) as b where b.uid = 222;
結果:
實現并列排名(相同分數排名相同):
SELECT obj.uid, obj.score, CASE WHEN @rowtotal = obj.score THEN @rownum WHEN @rowtotal := obj.score THEN @rownum :=@rownum + 1 WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1 END AS rownum FROM ( SELECT uid, score FROM testsort ORDER BY score DESC ) AS obj, (SELECT @rownum := 0 ,@rowtotal := NULL) r
查詢指定用戶并列排名:
SELECT total.* FROM (SELECT obj.uid, obj.score, CASE WHEN @rowtotal = obj.score THEN @rownum WHEN @rowtotal := obj.score THEN @rownum :=@rownum + 1 WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1 END AS rownum FROM ( SELECT uid, score FROM testsort ORDER BY score DESC ) AS obj, (SELECT @rownum := 0 ,@rowtotal := NULL) r) AS total WHERE total.uid = 222;
感謝你能夠認真閱讀完這篇文章,希望小編分享的“MYSQL如何實現排名及查詢指定用戶排名功能”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。