【发布时间】:2016-05-18 17:34:27
【问题描述】:
简介
我的游戏有一个使用排名的高分表。分数表表示当前的高分和玩家信息,最近的表表示用户最近发布的所有分数,这些分数可能是也可能不是新的最高分数。
排名下降是通过计算玩家的当前排名减去他们在达到最新最高分时的排名来计算的。
排名提升的计算方法是玩家在达到最新最高分时的排名减去他们在达到之前最高分时的排名。
最后,如代码中所写:$change = ($drop > 0 ? -$drop : $increase);
问题
我使用以下两个查询结合一些 PHP 代码来计算排名变化。它工作得很好,但有时有点慢。
有没有办法优化或组合这两个查询+PHP代码?
我为第一个查询创建了一个 SQL Fiddle:http://sqlfiddle.com/#!9/30848/1
表格已填满内容,因此不应更改其结构。
这是当前的工作代码:
$q = "
select
(
select
coalesce(
(
select count(distinct b.username)
from recent b
where
b.istopscore = 1 AND
(
(
b.score > a.score AND
b.time <= a.time
) OR
(
b.score = a.score AND
b.username != a.username AND
b.time < a.time
)
)
), 0) + 1 Rank
from scores a
where a.nickname = ?) as Rank,
t.time,
t.username,
t.score
from
scores t
WHERE t.nickname = ?
";
$r_time = 0;
if( $stmt = $mysqli->prepare( $q ) )
{
$stmt->bind_param( 'ss', $nick, $nick );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $r_rank, $r_time, $r_username, $r_score );
$stmt->fetch();
if( intval($r_rank) > 99999 )
$r_rank = 99999;
$stmt->close();
}
// Previous Rank
$r_prevrank = -1;
if( $r_rank > -1 )
{
$q = "
select
coalesce(
(
select count(distinct b.username)
from recent b
where
b.istopscore = 1 AND
(
(
b.score > a.score AND
b.time <= a.time
) OR
(
b.score = a.score AND
b.username != a.username AND
b.time < a.time
)
)
), 0) + 1 Rank
from recent a
where a.username = ? and a.time < ? and a.score < ?
order by score desc limit 1";
if( $stmt = $mysqli->prepare( $q ) )
{
$time_minus_one = ( $r_time - 1 );
$stmt->bind_param( 'sii', $r_username, $time_minus_one, $r_score );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $r_prevrank );
$stmt->fetch();
if( intval($r_prevrank) > 99999 )
$r_prevrank = 99999;
$stmt->close();
}
$drop = ($current_rank - $r_rank);
$drop = ($drop > 0 ? $drop : 0 );
$increase = $r_prevrank - $r_rank;
$increase = ($increase > 0 ? $increase : 0 );
//$change = $increase - $drop;
$change = ($drop > 0 ? -$drop : $increase);
}
return $change;
【问题讨论】:
-
也许切换到 PDO 会更快一些,但它可能不会做任何事情。
-
能否解释一下:
-
能否请您定义 1. 这两个表代表什么 & 2. 您的算法/数学用于计算排名?根据我的计算,我的排名是其他人最近得分并且比我在“分数”表中的记录更早(及时)发生的条目数量。加上忽略 !istopscoes
-
@gfunk 1. 分数表代表当前的高分和玩家信息,最近表代表用户最近发布的所有分数,这些分数可能是也可能不是新的最高分。 2.
rank drop是通过计算玩家当前的排名减去他们达到最近最高分时的排名。 --rank increase是通过计算玩家在达到最新最高分时的排名减去他们在达到上一次最高分时的排名来计算的。最后,如代码所写,$change = $increase - $drop;. -
包含样本数据以及预期结果以及对该预期结果的推理(即解释您的术语,如“排名”)可能有助于帮助其他人了解您正在尝试做什么并想出一个答案。 stackoverflow.com/help/how-to-ask
标签: php mysql sql mysqli combinations