MySQL Get Rank from Leaderboards

烂漫一生 提交于 2019-12-02 08:32:52

When the database executes this query, first it selects from Scores, filtering by name = '$name'.

Then, for every row, it executes the subquery:

(
 SELECT  COUNT(*)
   FROM    Scores ui
  WHERE   (ui.score, -ui.ts) >= (uo.score, -uo.ts)
) AS rank

It means that, for every row of Scoreswith the searched name, it searches how many records are in Scores where (ui.score, -ui.ts) is greater or equals to the current row's values.

I hope to have helped you...

A fact from algebra is that -A >= -B if-and-only-if A <= B.

So the expression (ui.score, -ui.ts) >= (uo.score, -uo.ts)

is just a fancy way of checking that ui.score >= ui.score AND ui.ts <= uo.ts.

The reason for including the timestamp is so that there's a "tie breaker" to uniquely define a rank.

I'm not sure if using the (A, -B) >= (A2, -B2) provides any performance advantage over just writing (A >= A2) AND (B <= B2).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!