我有一张球员名单:
id points last_online
1 320 2011-07-10
2 1025 2011-07-05
3 750 2011-04-25
4 5000 2011-07-10
5 525 2011-05-01
为了获得玩家等级(基于分数),我有以下mySQL选择:
SELECT Player.*,
( SELECT COUNT(*)
FROM players Player_i
WHERE (Player_i.points, Player_i.id) >= (Player.points, Player.id)
) AS rank
FROM players AS Player
WHERE Player.id = 1
工作正常。因此,玩家ID 1的等级为5。
但我想只考虑过去30天内上次在线的球员(考虑今天是2011-07-10)。这样,玩家ID 1的等级将是3,因为玩家3和5被排除在等级之外。
知道我该怎么做吗?
答案 0 :(得分:3)
两种方式。第一种方法,稍微编辑您的查询:
SELECT Player.*,
( SELECT COUNT(*)
FROM players Player_i
WHERE Player_i.points >= Player.points
and last_online > subdate(now(), '30 day')
) AS rank
FROM players AS Player
WHERE Player.id = 1
and last_online > subdate(now(), '30 day'); -- EDITED to add this line
第二种方式,以及更好的方式,是使用变量(方式更好的性能,更简单的SQL):
set @rank := 0;
SELECT *, @rank := @rank + 1
FROM Player
WHERE last_online > subdate(now(), 30 'day')
ORDER BY points desc;
答案 1 :(得分:1)
在您的查询中添加WHERE last_online > NOW() - '30 days'
:
SELECT Player.*,
( SELECT COUNT(*)
FROM players Player_i
WHERE (Player_i.points, Player_i.id) >= (Player.points, Player.id)
AND Player.last_online >= SUBDATE(NOW(), '30 day')
) AS rank
FROM players AS Player
WHERE Player.id = 1
AND Player.last_online >= SUBDATE(NOW(), '30 day');