前言
本文主要介紹了關(guān)于MYSQL實現(xiàn)排名及查詢指定用戶排名功能(并列排名功能)的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧
表結(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 = '測試排序'
ROW_FORMAT = DYNAMIC;
思路:可以先排序,再對結(jié)果進(jìn)行編號;也可以先查詢結(jié)果,再排序編號。
說明:
@rownum := @rownum + 1 中 := 是賦值的作用,這句話的意思是先執(zhí)行@rownum + 1,然后把值賦給@rownum;
(SELECT @rownum := 0) r 這句話的意思是設(shè)置rownum字段的初始值為0,即編號從1開始。
實現(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é)果:
實現(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;
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
您可能感興趣的文章:- Mysql排序獲取排名的實例代碼
- MySQL頁面訪問統(tǒng)計及排名情況
- MySQL中給自定義的字段查詢結(jié)果添加排名的方法
- mysql分組取每組前幾條記錄(排名) 附group by與order by的研究
- 總結(jié)幾種MySQL中常見的排名問題