Codeigniter中由distinct()或group_by()过滤的计数结果



我想用CI计算活动记录查询的结果(使用postgreSQL)。我使用的是count_all_results(),它适用于大多数查询,但在连接后使用distinct()group_by()时不行,因为count_all_results()忽略了这些函数。

这是对这个问题的修复,在最新的(2.1.3)稳定版本中尚未实现。https://github.com/EllisLab/CodeIgniter/commit/b05f506daba5dc954fc8bcae76b4a5f97a7433c1

当我尝试在当前版本中自己实现此修复时,没有完成额外的过滤。行数保持不变。

关于如何在当前版本中实现这一点,或其他方法来计算distinct()group_by()过滤的结果的提示?

    $this->db->select('COUNT(id)');
    $this->db->join();
    $this->db->distinct();
    $this->db->group_by();
//...etc ...
    $query = $this->db->get('mytable');
    return count($query->result()); 

    $this->db->join();
    $this->db->distinct();
    $this->db->group_by();
//...etc ...
    $query = $this->db->get('mytable');
    return $query->num_rows(); 

可以使用

$this->db->group_by();
否则

$this->db->distinct();

在我的例子中,目前使用Codeigniter 3.1.11,当执行count_all_results()时,distinct() 被考虑在内。然而,你必须使用这个函数,做一个$this->db->select("distinct x"),然后计数,将不适用distinct限制的记录计数。

享受Codeigniter提供的语法糖可以:

return $this->db->distinct()->select('non_unique_column')->count_all_results('your_table');

return $this->db->select('DISTINCT non_unique_column')->count_all_results('your_table');

但是请记住,呈现的SQL将是(根据您的数据库驱动程序有一些变化):

SELECT COUNT(*) AS "numrows"
FROM (
SELECT DISTINCT non_unique_column
FROM your_table
) CI_count_all_results

如果您的结果集不需要隔离不同的值,因为无论如何都会保证结果是唯一的,那么您可以简单地使用:

return $this->db->count_all_results('your_table');

这个更简单的代码将生成以下呈现的SQL:

SELECT COUNT(*) AS "numrows"
FROM "STL_PROPERTYME_PORTFOLIO"

无论如何实现,count_all_results()都将始终返回一个非负整数,而不必通过名称显式引用列。

最新更新