sql >> Base de Datos >  >> RDS >> Mysql

Cálculo de rango en PHP/MySQL

Si desea clasificaciones generales, lamentablemente debe ordenar toda la tabla. En pocas palabras, no puede conocer el rango de alguien en la tabla sin conocer los otros rangos en la tabla.

Dicho esto, si está preocupado por el rendimiento, aquí hay una solución bastante fácil:almacene en caché el resultado de su consulta de clasificación (¡tal vez en otra tabla MySQL!) Y consulte eso para todas sus lecturas. Cuando alguien publique una nueva puntuación, vuelva a calcular su tabla temporal. Puede vaciar periódicamente todos los registros por debajo de un cierto rango (por ejemplo, cualquier persona con un puntaje inferior a 100 se elimina de la tabla de puntajes) para mantener los cálculos rápidos, ya que nadie subiría de rango después de haber sido derribado por un puntaje más alto.

# 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;

Entonces, cada vez que quieras leer la clasificación de un juego:

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