mysql udal,在PHP / MySQL中计算等级

I've got a table in MySQL lets just say for example its got two fields Username, GameName and Score.

I want to calculate the rank of a user for an indivudal game name so I could do the query

SELECT * FROM scores WHERE `GameName` = 'Snake' ORDER BY `Score` DESC

to get a list of all users in order of highest to lowest and assign a number to each user.

But is there an easier way to get the rank for an indivdual user rather than selecting the entire table as that doesn't seem too efficient.

Thanks

解决方案

If you want overall rankings, you unfortunately have to sort the whole table. Simply put, you cannot know someone's rank in the table without knowing the other ranks in the table.

That said, if you are worried about performance, there's a fairly easily solution here - cache the result of your ranking query (maybe into another a MySQL table!), and query that for all your reads. When someone posts a new score, recalculate your temporary table. You can periodically flush all records under a certain rank (say, anyone ranking under 100 gets removed from the scores table) to keep recomputations fast, since nobody would ever climb in rank after being knocked down by a higher score.

# Create your overall leaderboards once

create table leaderboards (rank integer primary key, score_id integer, game varchar(65), user_id integer, index game_user_id_idx (game, user_id))

# To refresh your leaderboard, we'll query the ranks for the game into a temporary table, flush old records from scores, then copy

# the new ranked table into your leaderboards table.

# We'll use MySQL's CREATE TABLE...SELECT syntax to select our resultset into it directly upon creation.

create temporary table tmp_leaderboard (rank integer primary key auto_increment, score_id integer, game varchar(65), user_id integer)

select ID, GameName, UserID, from scores where GameName = '$game' order by score desc;

# Remove old rankings from the overall leaderboards, then copy the results of the temp table into it.

delete from leaderboards where game = '$game';

insert into leaderboards (rank, score_id, game, user_id)

select rank, score_id, game, user_id from tmp_leaderboard;

# And then clean up the lower scores from the Scores table

delete from scores join tmp_leaderboard on scores.id = tmp_leaderboard.score_id, scores.GameName = tmp_leaderboard.game where tmp_leaderboard.rank < 100;

# And we're done with our temp table

drop table tmp_leaderboard;

Then, whenever you want to read a rank for a game:

select rank from leaderboards where game = '$game' and user_id = '$user_id';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值