我有一个游戏的高分数据库,可以跟踪各个世界中的每一次游戏。我想做的是找出一些关于游戏的统计数据,然后根据彼此的世界(按播放次数排序)找到每个世界“排名”的位置。
到目前为止,我的所有统计数据都运行良好,但是我在查找每个世界的排名时遇到了问题。
我也很确定在三个单独的查询中执行此操作可能是一种非常缓慢的方法,并且可能会得到改进。
我有一个时间戳列(此处未使用)和数据库模式中索引的“world”列。这是我的来源的一部分:
function getStast($worldName) {
// ## First find the number of wins and some other data:
$query = "SELECT COUNT(*) AS total,
AVG(score) AS avgScore,
SUM(score) AS totalScore
FROM highscores
WHERE world = '$worldName'
AND victory = 1";
$win = $row['total'];
// ## Then find the number of losses:
$query = "SELECT COUNT(*) AS total
FROM highscores
WHERE world = '$worldName'
AND victory = 0";
$loss = $row['total'];
$total = $win + $loss;
// ## Then find the rank (this is the broken bit):
$query="SELECT world, count(*) AS total
FROM highscores
WHERE total > $total
GROUP BY world
ORDER BY total DESC";
$rank = $row['total']+1;
// ## ... Then output things.
}
我相信让我失败的特定代码行在 RANK 查询中,
WHERE total > $total
它不起作用是因为它不能接受计算的总数作为 WHERE 子句中的参数吗?
最后,有没有一种更有效的方法可以在单个 SQL 查询中计算所有这些?
最佳答案
我想您可能想使用“总计 > $总计”?
SELECT world, count(*) AS total
FROM highscores
GROUP BY world
having total > $total
ORDER BY total DESC
关于MySQL - 优化查询并根据列总和查找排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/800467/