group-by和count在codeigniter中计数不正确


group by and count is not counting correct in codeigniter

我在显示正确的计数(字段)时遇到问题。我正在尝试按字段分组,并希望按组和计数返回订单。

控制器是

    $this->load->library('pagination');
    $query = "SELECT usercode,count(usercode) AS co FROM tabs
    GROUP BY usercode ORDER BY co desc";
    $config['total_rows'] = $this->db->query($query)->num_rows();
    $config['num_links'] = '25';
    $config['uri_segment'] = 3;
    $config['base_url'] = base_url() . "/user/topCreators/";
    $config['per_page'] = '25';
    $config['anchor_class'] = " class='"number'" ";
    $config['cur_tag_open'] = "<a href='"#'" class='"number 
    current'" title='"Current Page'">";
    $config['cur_tag_close'] = "</a>";
    $this->pagination->initialize($config);
    if ($this->uri->segment(3) == FALSE){
        $offset = 0;
    }
    else
    {
        $offset = $this->uri->segment(4);
    }
    $limit = $config['per_page'];
    $data["total_records"] = $config['total_rows'];
    $data["page_links"] = $config["per_page"];

    $data["query"] = $this->db->query($query . " LIMIT $limit OFFSET $offset");
    $this->load->view("top_creators", $data);

我的视图文件是

   <?php foreach($query->result() as $me) {?>
   <?= $me->co?>  
   <?php }?>

co对于每个结果都将是相同的数字,因为您正在对表选项卡中的所有用户代码进行计数,因此您的排序将不起作用。它还使执行$this->db->query($query)->num_rows();变得多余,因为它与co 的值相同

您应该更详细地解释什么在您的案例中不起作用。


在我看来,处理分页时的最佳实践是使用SQL_CALC_FOUND_ROWS

基本上,这允许您运行一个查询,并通过获取总行数

// Main query with SQL_CALC_FOUND_ROWS
$row = $this->db->query("SELECT FOUND_ROWS() AS found")->row();
$config['total_rows'] = $row->found;

SQL_CALC_FOUND_ROWS统计所有行,但只返回LIMIT内的行。这可以减少对系统的查询(减少延迟),并且总是给出正确的total_rows,因为您从同一查询中获得值。