group by和count在countigniter中计数不正确

时间:2012-09-01 21:23:22

标签: php mysql 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 }?>

2 个答案:

答案 0 :(得分:1)

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

的值相同

答案 1 :(得分:0)

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


在我看来,处理分页时的最佳做法是使用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,因为您从同一查询中获取了值。