【问题标题】:How can I select highest score the correct way in MYSQL?如何在 MYSQL 中正确选择最高分?
【发布时间】:2011-07-16 01:30:07
【问题描述】:

我正在努力完成:

  • 以尽可能少的 SQL/PHP 方式选择得分最高的前 20 名用户。
  • 目前仍未考虑缓存。

到目前为止我做了什么:

我能够检索所有 5k+ 记录及其分数,但不能限制为仅检索或计算前 20 名(示例)。

表格:

用户(ID、姓名) score_rec (id, uid, points) 此表为每个用户提供多个条目。最高分数将是具有最高数量的行、条目的分数。示例:UID 23 可能有 5 行属于它,他的分数是 5。

代码示例:

$query = "SELECT * FROM score_rec,users where users.id = score_rec.uid";
    $result = mysql_query($query);

    $array1 = Array();

    while($row = mysql_fetch_array($result) )
        {
            //Count their scores
            $query2 = "SELECT users.id,users.name,score_rec.uid FROM `score_rec`,`users` where score_rec.uid = $row[uid] and users.id = $row[uid]";
            $result2 = mysql_query($query2);

            $scores_count = mysql_num_rows($result2);                

            $array1["$row[name]"] = $scores_count;      

        }

我认为这可能通过临时表脚本、存储过程或可以查看两个表的简单查询来实现。由于 score_rec 可以单独用于计算最高条目持有者,因此一个查询可能足以满足两个表。

感谢大家提供的任何指导。

【问题讨论】:

  • 感谢大家的快速回复,谢谢。所有答案都很好。

标签: php mysql sql arrays


【解决方案1】:

这样的事情怎么样:

select users.id, count(*) as score
from users
    inner join score_rec on users.id = score_rec.uid
group by users.id
order by count(*) desc
limit 20

这将:

  • 对于每个用户,计算他有多少行(因为group by
  • 按行数对所有用户进行降序排序
  • 保留前 20 个结果行 - 这是行数较多的 20 个用户

【讨论】:

  • 很好的解释@Pascal,现在我对sql的理解好多了。谢谢。
【解决方案2】:

取决于你想要的分数:

1) 全球前 20 名得分,可能是重复用户:

SELECT users.id, users.name, score_rec.points
FROM users
LEFT JOIN score_rec ON users.id = score_rec.uid
ORDER BY score_rec.points DESC;

2) 前 20 名不同球员的得分:

SELECT DISTINCT users.id, ...
etc...

【讨论】:

    【解决方案3】:
    $query = "
        SELECT users.id,users.name,count(*) score
        FROM score_rec
        INNER JOIN users on users.id = score_rec.uid
        GROUP BY users.id,users.name
        ORDER BY score DESC
        LIMIT 20
        ";
    $result = mysql_query($query);
    $array1 = Array();
    
    while($row = mysql_fetch_array($result) )
        {
            $array1["$row[name]"] = $row['score'];
        }
    

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      相关资源
      最近更新 更多