這篇文章主要介紹了MySQL如何實(shí)現(xiàn)排名及查詢指定用戶排名功能,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
10年積累的成都網(wǎng)站建設(shè)、成都做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有新豐免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
表結(jié)構(gòu):
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 '分?jǐn)?shù)', PRIMARY KEY (id) ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = '測(cè)試排序' ROW_FORMAT = DYNAMIC;
思路:可以先排序,再對(duì)結(jié)果進(jìn)行編號(hào);也可以先查詢結(jié)果,再排序編號(hào)。
說明:
@rownum := @rownum + 1 中 := 是賦值的作用,這句話的意思是先執(zhí)行@rownum + 1,然后把值賦給@rownum;
(SELECT @rownum := 0) r 這句話的意思是設(shè)置rownum字段的初始值為0,即編號(hào)從1開始。
實(shí)現(xiàn)排名:
方法一:
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;
結(jié)果:
查看指定用戶排名:
方法一:
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;
結(jié)果:
實(shí)現(xiàn)并列排名(相同分?jǐn)?shù)排名相同):
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;
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“MYSQL如何實(shí)現(xiàn)排名及查詢指定用戶排名功能”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!