dongzhen6554 2012-02-11 23:15
浏览 50
已采纳

平均得分排名前5位?

I'm quite new to PHP and CodeIgniter, so please excuse me for posting up such an elementary question!

I have a system in place on my website where users can score games out of 10. These scores are stored in a table called game_vote which has the columns id, game_id, user_id and score - so it's relatively straight forward.

What I would like to do is, return the top 5 overall scores PER game. So I guess I need to fetch the average score for each game_id, order those averages in descending order, and then limit my results to 5.

Here is my controller so far:

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();

            }

        }

    }

}

I feel like I'm kind of on the right track.

Thanks in advance for any help on this.

Cheers!

[EDIT] AND HERE'S THE FINISHED FUNCTION IN CASE ANYBODY NEEDS IT IN THE FUTURE. :)

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();

    }

}
  • 写回答

1条回答 默认 最新

  • duanbage2161 2012-02-11 23:29
    关注

    I think this is the query you're looking for:

    select game_id, avg(score) ScoreAverage from game_vote
    group by game_id
    order by ScoreAverage desc
    limit 5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?