3

我在数据库中有一个表:

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;

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

4

2 回答 2

2

只需按自己的分组结果:

$res = $this->db->query("SELECT count(1) AS games,own FROM ownership WHERE user = ? GROUP BY own", array($user))->result_array();
于 2012-08-13T13:05:18.397 回答
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;
}
于 2012-08-13T13:55:01.060 回答