You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CodeIgniter中通过关联查询或子查询统计MySQL父子表子记录数

在CodeIgniter中实现关联表的分组统计查询

你需要的是把parent表和child表关联,统计每个parent对应的child记录数,这在CodeIgniter里有两种很实用的实现方式,我给你一步步说明:

方法一:LEFT JOIN + GROUP BY 分组统计

这种方式比较直观,通过左连接保留所有parent记录(哪怕没有对应的child也能显示count为0),再通过分组统计每个parent下的child数量。

在CodeIgniter的Model里可以这么写:

public function get_parent_with_child_count() {
    // 选择parent表的字段,用IFNULL处理无对应child的情况,避免返回NULL
    $this->db->select('parent.pid, parent.pitem, IFNULL(COUNT(child.cid), 0) AS child_count');
    // 左连接child表,关联条件为parent.pid = child.pid
    $this->db->join('child', 'parent.pid = child.pid', 'LEFT');
    // 按parent的pid分组,确保每个parent只返回一条统计结果
    $this->db->group_by('parent.pid');
    // 执行查询并返回结果数组
    return $this->db->get('parent')->result_array();
}

调用这个方法后,得到的结果就完全符合你的需求:

Array(
    [0] => Array(
        'pid' => 1,
        'pitem' => 'a',
        'child_count' => 3
    ),
    [1] => Array(
        'pid' => 2,
        'pitem' => 'b',
        'child_count' => 2
    ),
    [2] => Array(
        'pid' => 3,
        'pitem' => 'c',
        'child_count' => 1
    )
)

方法二:使用子查询实现

如果更倾向于用子查询的方式,也可以在SELECT语句中嵌套子查询来统计每个parent对应的child数量:

public function get_parent_with_child_count_subquery() {
    // 先构建子查询:统计每个pid对应的child记录数
    $subquery = $this->db->select('pid, COUNT(cid) AS count')
                         ->from('child')
                         ->group_by('pid')
                         ->get_compiled_select();
    
    // 主查询:关联parent表和子查询的统计结果
    $this->db->select('parent.pid, parent.pitem, IFNULL(sub.count, 0) AS child_count');
    $this->db->join("($subquery) AS sub", 'parent.pid = sub.pid', 'LEFT');
    return $this->db->get('parent')->result_array();
}

这个方法的逻辑是先通过子查询得到所有有child的pid的统计数,再和parent表左连接,同样能得到符合要求的结果。

如果你的业务场景中每个parent一定有对应的child,也可以把LEFT JOIN换成INNER JOIN,不过LEFT JOIN的兼容性更好,能覆盖所有边界情况。

内容的提问来源于stack exchange,提问作者justmasif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:28:59