如何在CodeIgniter查询中仅当C.bundle_status=3时对bundle_product_id分组
实现方案
CodeIgniter框架下可以根据你的业务场景选择以下两种实现方式:
场景1:同一个$inv_ID对应的所有tbl_inventory_items记录bundle_status值统一
这种情况优先选择先查询对应状态、再拼接查询条件的方案,性能更高逻辑更易懂:
// 第一步:先查询当前 inventory_id 对应的 bundle_status 值 $status_info = $this->db->select('bundle_status') ->get_where('tbl_inventory_items', ['inventory_id' => $inv_ID]) ->row(); $bundle_status = $status_info ? $status_info->bundle_status : 0; // 第二步:执行原有查询,按需添加分组逻辑 $this->db->select('C.product_id, A.customer_name, A.contact_number, A.email_id, A.country_area_id, A.sub_area_id, A.building_no, A.landmark, A.alternative_number, A.timing, A.order_comments, A.latitude, A.longitude, A.shipping_charge, B.stock_item_stock, C.bundle_status, C.bundle_product_id'); $this->db->from('tbl_inventory_items as C'); $this->db->join('tbl_stock as B','B.stock_item_id=C.product_id and B.stock_status=0','left'); $this->db->join('tbl_inventory as A','C.inventory_id=A.inventory_id','left'); $this->db->where('C.inventory_id',$inv_ID); // 状态为3时添加分组 if ($bundle_status == 3) { $this->db->group_by('C.bundle_product_id'); } // 执行查询获取结果 $result = $this->db->get()->result();
场景2:同一个$inv_ID下存在多种bundle_status的记录,需要按行级别判断是否分组
如果需要在单条SQL里根据每行的bundle_status动态决定分组逻辑,可以直接在group_by方法里写CASE条件:
// 在原有查询的where条件后添加以下代码即可 $this->db->group_by('CASE WHEN C.bundle_status = 3 THEN C.bundle_product_id ELSE C.product_id END');
*注意:如果你的数据库开启了ONLY_FULL_GROUP_BY模式,需要保证SELECT查询的非聚合字段都出现在GROUP BY中,或者使用ANY_VALUE()函数包裹不需要聚合的字段,避免SQL报错。
内容的提问来源于stack exchange,提问作者ahamed a
相关产品推荐
相关产品推荐

