CodeIgniter和计算数据库中的特定行

时间:2012-08-13 12:23:37

标签: php mysql codeigniter

我在数据库中有一个表:

id      |   int(25) Auto Increment   
game    |   int(10)  
user    |   int(9)   
own     |   int(11)  
userrate|   int(2)   
time    |   datetime    

我现在想要的是计算所有own类型的行。我知道这很难理解,所以我会发一个例子:

 - own: 1; count: 5;
 - own: 2; count: 3;
 - own: 4; count: 10;

我最初的想法是为每个own创建不同的查询(因为它只有四个),如下所示:

    $this->db->where('user',$user);
    $this->db->from('ownership');
    $this->db->where('own','1');

    $whole = $this->db->count_all_results();

    return $whole;

但我认为这根本不好。你能告诉我正确的方法吗?

2 个答案:

答案 0 :(得分:2)

只需按结果分组结果:

$res = $this->db->query("SELECT count(1) AS games,own FROM ownership WHERE user = ? GROUP BY own", array($user))->result_array();

答案 1 :(得分:2)

我解决了这个问题。它与@ vearutop的解决方案类似,但它返回一个数组own - count

以下是模型:

public function countRates($user) {
    $this->db->select('own, COUNT(own) as count');
    $this->db->where('user',$user);
    $this->db->from('ownership');
    $this->db->group_by('own');

    $q = $this->db->get();
    $q = $q->result_array();

    return $q;
}