【问题标题】:Top 5 average scores?平均分前 5 名?
【发布时间】:2012-03-03 22:23:54
【问题描述】:

我对 PHP 和 CodeIgniter 还很陌生,所以请原谅我发布了这么简单的问题!

我的网站上有一个系统,用户可以在 10 分中对游戏进行评分。这些分数存储在一个名为 game_vote 的表中,其中包含 id、game_id、user_id 和 score 列 - 所以它相对简单。

我想做的是,返回每场比赛的前 5 名总得分。所以我想我需要获取每个 game_id 的平均分数,按降序排列这些平均值,然后将我的结果限制为 5。

到目前为止,这是我的控制器:

function get_all_game_ratings()

{

    $this->db->select('game_vote.game_id, game_vote.score, game.title');
    $this->db->from('game_vote');
    $this->db->join('game', 'game.id = game_vote.game_id');
    $this->db->group_by('game_vote.game_id');
    $this->db->where('game_vote.game_id', 2);
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        foreach ($query->result() as $row)

        {

            $this->db->select('game_vote.game_id, game_vote.score, game.title');
            $this->db->select_avg('game_vote.score');
            $this->db->join('game', 'game.id = game_vote.game_id');
            $this->db->from('game_vote');
            $this->db->where('game_vote.game_id', $row->game_id);
            $query = $this->db->get();

            if ($query->num_rows() > 0)

            {

                return $query->result();

            }

        }

    }

}

我觉得自己走在了正确的轨道上。

提前感谢您对此提供的任何帮助。

干杯!

[编辑] 这是已完成的功能,以防将来有人需要它。 :)

function get_user_ratings($limit)

{

    $this->db->select('game_vote.game_id, game_vote.score, game.title');
    $this->db->select_avg('game_vote.score');
    $this->db->group_by('game_vote.game_id');
    $this->db->from('game_vote');
    $this->db->join('game', 'game.id = game_vote.game_id');
    $this->db->order_by('AVG(game_vote.score)', 'desc');
    $this->db->limit($limit);
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        return $query->result();

    }

}

【问题讨论】:

  • AVG(game_vote.score) 也应该在 SELECT 列表中。

标签: php sql codeigniter


【解决方案1】:

我认为这是您要查找的查询:

select game_id, avg(score) ScoreAverage from game_vote
group by game_id
order by ScoreAverage desc
limit 5

【讨论】:

  • 谢谢,伙计。我现在将编辑我的函数的代码。一切正常。
猜你喜欢
  • 1970-01-01
  • 2018-05-12
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
相关资源
最近更新 更多