首页 > 解决方案 > 如果字段不为空,则 Codeigniter 分组

问题描述

我有以下查询:

$this->db->select('SUM(cost_price) AS cost_price,SUM(cost_price) AS total,employees.username AS staff_name');
        $this->db->from('items');
        $this->db->join('customers', 'customers.person_id = items.customer_id');
        $this->db->join('employees', 'employees.person_id = items.staff_id');
        $this->db->join('people', 'people.person_id = customers.person_id');
 $this->db->group_by('items.is_serialized');

在项目表中,我有一个名为 is_serialized 的字段,我想将在 is_serialized 字段中具有值的所有行分组,但如果该行为 NULL,则不分组,是否可以使用我的查询来这样做?

标签: mysqlcodeigniter

解决方案


在 group by 子句中使用“CASE”函数仅检查非空值。

例如:

 $this->db->group_by("CASE WHEN items.is_serialized IS NOT NULL THEN items.is_serialized END",FALSE);

推荐阅读