I have a votes table that holds votes. I need to get the amount of votes each user has in the table based on their id and then sort the query by who has the most votes. Basically a leaders table. How would I do that?
Say your table that stores all the votes is called activity
, it stores the id
and user_id
.
Getting the vote totals:
select user_id, count(user_id) as votes from activity group by user_id;
Get the top 5 vote getters:
select user_id, count(user_id) as votes from activity group by user_id ORDER BY votes desc LIMIT 5;
$this->db->select('COUNT(user_id) AS total_votes');
$this->db->from('votes');
$this->db->group_by('user_id');
$this->db->order_by('total_votes DESC');
$result = $this->db->get()->result();