我的架构
我有以下表格
table notes/example values
------------------------------------------------
users (
id
email # "foo@example.com"
)
games (
id
name # "Space Invaders", "Asteroids", "Centipede"
)
players (
id
name # "uber dude"
user_id # player belongs to user
game_id # player belongs to game
)
scores (
id
player_id # belongs to one player
value # 50
created_at # "2010-09-10", "2010-08-05"
month # "2010-09", "2010-08"
)
我需要创建两个报告。
1) 顶级球员
最近 4 个月表现最好的球员(每位球员的所有得分之和)。显示每个月的前 10 名。
2010-07 2010-08 2010-09 2010-10
1 plyA 5,000 pts plyB 9,400 pts ... ...
Centipede Solitaire
2 plyB 3,600 pts plyC 8,200 pts ... ...
Asteroids Centipede
3 plyC 2,900 pts plyA 7,000 pts ... ...
Centipede Centipede
4 ... ... ... ...
5 ... ... ... ...
6 ... ... ... ...
7 ... ... ... ...
8 ... ... ... ...
9 ... ... ... ...
10 ... ... ... ...
2) 热门用户:
最近 4 个月内表现最好的用户(每个用户的每个玩家的所有得分总和)。显示每个月的前 10 名。
2010-07 2010-08 2010-09 2010-10
1 userA 50,000 pts userB 51,400 pts ... ...
2 userB 40,500 pts userA 39,300 pts ... ...
3 userC 40,200 pts userC 37,000 pts ... ...
4 ... ... ... ...
5 ... ... ... ...
6 ... ... ... ...
7 ... ... ... ...
8 ... ... ... ...
9 ... ... ... ...
10 ... ... ... ...
MySQL 视图助手
出于加入目的,我有一个存储视图来帮助查询报告的月份。它将始终返回最近的 4 个月。
report_months (
month
)
SELECT * FROM report_months;
2010-07
2010-08
2010-09
2010-10
问题
例如,在报告 #1 中,我可以很容易地得到总和。
select
p.name as player_name,
g.name as game_name,
s.month as month,
sum(s.score) as sum_score
from players as p
join games as g
on g.id = p.game_id
join scores as s
on s.player_id = p.id
join report_months as rm -- handy view helper
on rm.month = s.month
group by
p.name, g.name
order by
sum(s.score) desc
-- I can't do this :(
-- limit 0, 40
但是,我不能简单地获取前 40 个结果并将它们分散到 4 个月,因为这不能保证我每个月都有 10 个。
问题
如何修改我的查询以确保每个月获得 10 个?