我有一张持有选票的投票表。我需要根据用户的ID获取每个用户在表中的投票数量,然后按谁拥有最多票数对查询进行排序。基本上是领导者表。我该怎么做?
答案 0 :(得分:1)
$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();
答案 1 :(得分:0)
假设您存储所有投票的表名为activity
,它会存储id
和user_id
。
获得总票数:
select user_id, count(user_id) as votes from activity group by user_id;
获得前5名获胜者:
select user_id, count(user_id) as votes from activity group by user_id ORDER BY votes desc LIMIT 5;