CodeIgniter查询:筛选仅购买单一品类产品的客户
数据表结构
customers表
| id | name | |
|---|---|---|
| 1 | richa | richa@gmail.com |
| 2 | sam | sam@gmail.com |
| 3 | hella | hella@gmail.com |
orders表
| id | customer_id |
|---|---|
| 101 | 1 |
| 102 | 2 |
| 103 | 3 |
order_product表
| id | order_id | product_id |
|---|---|---|
| 101 | 1 | |
| 102 | 1 | |
| 103 | 2 |
products表
| id | product_name |
|---|---|
| 1 | Mobile |
| 2 | AC |
| 3 | Fridge |
需求说明
筛选出仅购买一种类型产品的客户(可多次购买同一品类,但从未购买其他品类产品)。
原代码问题分析
- 语法错误:
->where('order_products.product_id', > 0);写法完全错误,CodeIgniter的where方法不支持这种参数格式,且该条件无实际意义(所有product_id都是正整数)。 - 表名不一致:原代码中用了
order_products,但实际表名是order_product,会导致关联失败。 - 核心逻辑缺失:仅按客户ID分组,但没有统计每个客户购买的产品品类数量,完全没实现“仅购买一种类型”的筛选逻辑。
- 未执行查询:代码最后直接返回查询构建器对象,没有调用
get()方法执行查询并获取结果集。
正确实现思路
- 关联
customers、orders、order_product三张表,确保表名正确。 - 按客户ID分组,同时统计每个客户对应的唯一产品ID的数量(用
COUNT(DISTINCT product_id))。 - 筛选出唯一产品数量等于1的客户。
- 执行查询并返回结果数组。
正确CodeIgniter代码实现
// 构建查询 $query = $this->db->table('customers') ->join('orders', 'orders.customer_id = customers.id') ->join('order_product', 'order_product.order_id = orders.id') // 修正表名 ->select('customers.id, customers.name, customers.email, COUNT(DISTINCT order_product.product_id) as product_type_count') ->groupBy('customers.id') ->having('product_type_count', 1); // 筛选仅购买一种品类的客户 // 执行查询并获取结果数组 $resultArr = $query->get()->result_array(); return $resultArr;
代码说明
COUNT(DISTINCT order_product.product_id):统计每个客户购买的不同产品品类数量,去重后计数,确保多次购买同一品类只算1种。having('product_type_count', 1):分组后筛选出品类数量为1的客户,这是实现需求的核心条件。get()->result_array():执行查询并将结果转为数组返回,替代原代码直接返回构建器对象的错误写法。
内容的提问来源于stack exchange,提问作者Goldy-566
相关产品推荐
相关产品推荐

