Reputation: 120
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();
}
}
Upvotes: 2
Views: 257
Reputation: 43464
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
Upvotes: 1