创建用户排名系统,如SO与分页

时间:2014-03-15 07:21:33

标签: mysql sql pagination

我尽力搜索但失败了。我正在开发一个应用程序,我必须根据他们的分数制作一个系统来排名用户,就像SO一样。搜索完SO后,我发现此查询创建了排名系统

SELECT    uid,score,
          @curRank := @curRank + 1 AS rank
FROM      rankTable p, (SELECT @curRank := 0) r
ORDER BY  score desc

但是如何使此查询返回特定用户的排名,例如http://stackexchange.com/leagues/1/month/stackoverflow/2014-03-01?sort=totalreputation

我无法理解这一点。

简而言之,我只想制作一个排名系统就像拥有500万用户的SO一样。任何建议的逻辑都表示赞赏。

我正在MySQL,PHP和节点上开发它。

2 个答案:

答案 0 :(得分:0)

我尝试了以下查询,它的工作原理是希望它能解决您的查询问题。我也在共享我用过的数据集

DATASET

CREATE TABLE rankTable (uid varchar(10) not null ,score int)
insert into rankTable values('a',5)
insert into rankTable values('b',2)
insert into rankTable values('c',10)

查询

SELECT * FROM
(
SELECT    uid,score,
          @curRank := @curRank + 1 AS rank
FROM      rankTable p, (SELECT @curRank := 0) r
ORDER BY  score desc
) z where uid = 'b'

限制回复

SELECT * FROM
(
SELECT    uid,score,
          @curRank := @curRank + 1 AS rank
FROM      rankTable p, (SELECT @curRank := 0) r
ORDER BY  score desc
) z where uid = 'b'
LIMIT 0*@PageNum , 30

如果您显示所有列表,那么

SELECT * FROM
(
SELECT    uid,score,
          @curRank := @curRank + 1 AS rank
FROM      rankTable p, (SELECT @curRank := 0) r
ORDER BY  score desc
) z LIMIT 0*@PageNum , 30

答案 1 :(得分:0)

尝试此查询以获得MySQL中的排名:

SELECT t4.uid,t4.score,
case when t4.score2 = t4.score3 then @Rank else
@Rank := @Rank + 1 end as rank FROM
(SELECT t2.*,t2.score score2,t3.score score3 FROM
(SELECT t1.*, @ROWNUM := @ROWNUM + 1 rn FROM
(SELECT uid,score FROM rankTable ORDER BY  score desc)t1,
(SELECT @ROWNUM := 0) r)t2 left outer join
(SELECT t1.*, @ROWNUM1 := @ROWNUM1 + 1 rn FROM
(SELECT uid,score FROM rankTable ORDER BY  score desc)t1,
(SELECT @ROWNUM1 := 0) r1)t3
on t2.rn = t3.rn + 1)t4,
(SELECT @Rank := 0) ra;

<强> SQL Fiddle

也许这个查询工作得更快:

SELECT t2.*, t1.ranks FROM
(SELECT    Score, @rank:=@rank+1 Ranks FROM
(SELECT  DISTINCT Score FROM    rankTable a
ORDER   BY score DESC) t, (SELECT @rank:= 0)r)t1 
INNER JOIN rankTable t2 ON t2.score = t1.score;

<强> SQL Fiddle