codeigniter 中 count() 和 sum() 通过 query builder 实现:count_all() 全表统计,count_all_results() 支持 where 条件;sum 需用 select('sum(field) as alias') 配合 get() 获取,返回结果需空值处理(如 ?? 0),ci4 新增 selectsum() 方法。

CodeIgniter 中统计数量(count)和求和(sum)主要通过 Query Builder(查询构造器)实现,无需手写原生 SQL,简洁安全。
count() 统计记录数
用于获取满足条件的行数,返回整型结果。常用于分页总数、状态统计等场景。
- 基础用法:统计用户表总记录数
$this->db->from('users');
$count = $this->db->count_all(); // 不带条件,全表统计
```
- 带条件统计:统计已激活用户数量
$this->db->from('users');
$this->db->where('status', 1);
$count = $this->db->count_all_results(); // 必须用 count_all_results() 配合 where
```
- 注意:
count_all()不支持 where 条件;带条件必须用count_all_results() - 也可链式调用:
$this->db->where(...)->from(...)->count_all_results()
sum() 对字段求和
对数值型字段执行 SUM 聚合运算,返回 float 或 int 类型结果。
- 单字段求和:统计订单总金额
$this->db->select('SUM(amount) as total');
$this->db->from('orders');
$query = $this->db->get();
$result = $query->row();
$total = $result->total ?? 0;
```
- 结合条件与分组:按用户统计消费总额
$this->db->select('user_id, SUM(amount) as total_spent');
$this->db->from('orders');
$this->db->where('status', 'completed');
$this->db->group_by('user_id');
$query = $this->db->get();
$results = $query->result();
```
- 务必用
select()显式指定 SUM 表达式,并给别名,方便取值 - 聚合函数需配合
get()执行,不能直接用sum()方法(CI 没有独立的 sum() 方法)
更简洁的写法(推荐)
利用方法链和数组返回简化代码:
```php// 统计有效订单数
$order_count = $this->db
->from('orders')
->where('status', 'paid')
->count_all_results();
// 计算总销售额
$total_sales = $this->db
->select('SUM(amount) as sales')
->from('orders')
->where('status !=', 'cancelled')
->get()
->row()->sales ?? 0;
```
- 避免冗余变量,一行链式更清晰
- 使用
?? 0防止空结果报错 - 注意:sum 查询若无匹配记录,结果为 NULL,需做空值处理
注意事项
- CodeIgniter 3 和 4 的 Query Builder 基本一致,但 CI4 支持更丰富的聚合方法(如
selectSum()),CI3 仍需靠select()手动写 SUM - 避免在循环中反复调用 count/sum 查询,应提前查好或使用缓存
- 大数据量时注意加索引——特别是 where 字段和 sum 字段(如 amount)











