计算每个组中的行数

时间:2022-01-15 02:12:25

Using CodeIgniter's Active Record class and MySQL, I have a table of posts with user_id and various other fields, and I want to count how many posts each user has made. I could get rows where user_id = $whatever and count the number of results, but I'd have to loop through every user_id and use that count_all_results() query over and over for each one.

使用CodeIgniter的Active Record类和MySQL,我有一个包含user_id和各种其他字段的帖子表,我想计算每个用户发了多少帖子。我可以获取user_id = $ whatever的行并计算结果的数量,但是我必须循环遍历每个user_id并对每个user_id反复使用count_all_results()查询。

There must be a better way! If every field just had a field with a 1 in it, I could select_sum up that field and get a count. But that seems dumb.

肯定有更好的办法!如果每个字段只有一个带有1的字段,我可以选择该字段并获得计数。但这似乎是愚蠢的。

Many thanks in advance!

提前谢谢了!

1 个解决方案

#1


Using active record should be:

使用活动记录应该是:

$this->db->select('field1, ... ,fieldn, count(1) as number_elements_of_row');

$this->db->group_by(array('field_group_1', ... ,'field_group_n'));

$result = $this->db->get('mytable');

so $result will have what you need!

所以$ result将拥有你所需要的!

#1


Using active record should be:

使用活动记录应该是:

$this->db->select('field1, ... ,fieldn, count(1) as number_elements_of_row');

$this->db->group_by(array('field_group_1', ... ,'field_group_n'));

$result = $this->db->get('mytable');

so $result will have what you need!

所以$ result将拥有你所需要的!