如何在代码点火器中对 COUNT 查询执行 num_rows()


How to do a num_rows() on COUNT query in codeigniter?

这有效:

        $sql = "SELECT id
                FROM `users`
                WHERE `account_status` = '" . $i . "'"; 
        $query = $this->db->query($sql);
        var_dump($query->num_rows());

但这不会:

        $sql = "SELECT COUNT(*)
                FROM `users`
                WHERE `account_status` = '" . $i . "'"; 
        $query = $this->db->query($sql);
        var_dump($query->num_rows());

如何对 COUNT(*) 查询进行num_rows?第二种方式是否在性能方面做得更好?

执行COUNT(*)只会给你一个包含行数的单数行,而不是结果本身。

要访问您需要执行的COUNT(*)

$result = $query->row_array();
$count = $result['COUNT(*)'];

第二个选项的性能要好得多,因为它不需要将数据集返回给 PHP,而只需要一个计数,因此更加优化。

在CI中,实际上非常简单,您所需要的只是

$this->db->where('account_status', $i);
$num_rows = $this->db->count_all_results('users');
var_dump($num_rows); // prints the number of rows in table users with account status $i
$query->num_rows()

查询返回的行数。注意:在此示例中,$query是将查询结果对象分配给的变量:

$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();

COUNT() 查询上的num_rows字面上总是 1。它是一个没有 GROUP BY 子句的聚合函数,因此所有行都组合成一个。如果你想要计数的值,你应该给它一个标识符SELECT COUNT(*) as myCount ...,然后使用你的常规方法来访问结果(第一个,唯一的结果)并获取它的'myCount'属性。

根据 CI 文档,我们可以使用以下内容,

$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();

如果我们想在没有任何条件的情况下获取表中的总行数,则使用简单

echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table
这是我

解决上述给定问题的方法

$this->db->select('count(id) as ids');
$this->db->where('id', $id);
$this->db->from('your_table_name');

谢谢

这只会返回 1 行,因为您只是选择一个COUNT()。 在这种情况下,您将在$query上使用mysql_num_rows()

如果要获取每个ID的计数,请将GROUP BY id添加到字符串的末尾。

在性能方面,永远不要在查询中使用*。如果表中有 100 个唯一字段,并且您想获取所有字段,则写出所有 100 个字段,而不是* 。这是因为*每次抓取一个字段时都必须重新计算它必须去多少个字段,这需要更多的时间来调用。

我建议不要使用相同的参数进行另一个查询,而是立即运行SELECT FOUND_ROWS()

    $list_data = $this->Estimate_items_model->get_details(array("estimate_id" => $id))->result();
    $result = array();
    $counter = 0;
    $templateProcessor->cloneRow('Title', count($list_data));
    foreach($list_data as $row) {
        $counter++;
        $templateProcessor->setValue('Title#'.$counter, $row->title);
        $templateProcessor->setValue('Description#'.$counter, $row->description);
        $type = $row->unit_type ? $row->unit_type : "";
        $templateProcessor->setValue('Quantity#'.$counter, to_decimal_format($row->quantity) . " " . $type);
        $templateProcessor->setValue('Rate#'.$counter, to_currency($row->rate, $row->currency_symbol));
        $templateProcessor->setValue('Total#'.$counter, to_currency($row->total, $row->currency_symbol));   
    }