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

求助:在CodeIgniter中按销量获取TOP5产品的实现方法

解决CodeIgniter按销量获取TOP5产品的问题

方法一:原生mysqli查询的问题与修正

你的原生代码存在两处问题:

  1. 重复执行$conn->query($total),第一次赋值后第二次又在判断逻辑里重新执行,属于冗余操作且可能引发异常;
  2. 遍历结果集的方式错误,mysqli_result对象不能直接用foreach遍历,需要用fetch_assoc()方法循环获取数据。

修正后的代码:

$conn = new mysqli("localhost", "root","","bubblebee");
if ($conn->connect_errno) { 
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
} else {
    echo 'Connection success <br>' ;
}

$total = "SELECT product_id, SUM(amount) 
            FROM order_items 
            GROUP BY product_id 
            ORDER BY SUM(amount) DESC 
            LIMIT 5"; // 改为目标TOP5

$statement = $conn->query($total);
if (!$statement) {
    echo 'Query failed: ' . $conn->error;
} else {
    while ($row = $statement->fetch_assoc()) { // 改用while循环读取结果
        echo $row['product_id'] . '<br>';
    }
    $statement->free(); // 释放结果集资源
}
$conn->close(); // 关闭数据库连接

方法二:CodeIgniter查询构造器的问题与修正

你的构造器查询核心错误是排序字段错误——你按products.id倒序,而非按销量总和sum(order_items.amount)倒序;另外left join会包含无订单记录的产品(销量为0),如果只需要统计有销量的产品,建议改用inner join,同时要保证group_by字段符合SQL严格模式要求(需包含所有非聚合字段)。

修正后的代码:

$select = array(
    'products.id',
    'products.name as label', 
    'sum(order_items.amount) as total_sales'
);
$final = $this->db->select($select)
       ->from('products') 
       ->join('order_items', 'order_items.product_id = products.id', 'inner') // 仅保留有销量的产品
       ->group_by('products.id, products.name') // 严格模式下需包含所有非聚合字段
       ->order_by('total_sales', 'DESC') // 按销量总和倒序排序
       ->limit(5) 
       ->get()
       ->result_array();

更简便的方案:直接执行原生SQL

既然你已经有可正常运行的原生SQL,也可以直接用CodeIgniter的query()方法执行,避免构造器的语法细节问题:

// 仅获取产品ID和销量
$sql = "SELECT product_id, SUM(amount) as total_sales 
        FROM order_items 
        GROUP BY product_id 
        ORDER BY total_sales DESC 
        LIMIT 5";
$query = $this->db->query($sql);
$top_products = $query->result_array();

// 如果需要关联产品名称,使用关联查询
$sql = "SELECT p.id, p.name, SUM(oi.amount) as total_sales
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        GROUP BY p.id, p.name
        ORDER BY total_sales DESC
        LIMIT 5";
$query = $this->db->query($sql);
$top_products = $query->result_array();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:15:48