如何使用Sequelize查询销量最高及出现频次最多的商品
前置说明
假设你已定义的关联关系如下(和实际定义对齐即可):
const { DataTypes } = require('sequelize'); // 商品模型 const Product = sequelize.define('Product', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING, // 其余商品字段按需补充 }); // 订单明细模型 const OrderItem = sequelize.define('OrderItem', { orderID: DataTypes.INTEGER, productID: DataTypes.INTEGER, quantity: DataTypes.INTEGER, }); // 关联关系 Product.hasMany(OrderItem, { foreignKey: 'productID' }); OrderItem.belongsTo(Product, { foreignKey: 'productID' });
需求1:查询销量最高的商品
按productID分组统计quantity总和,倒序排序后取第一条即可:
const topSalesProduct = await OrderItem.findOne({ attributes: [ 'productID', [sequelize.fn('SUM', sequelize.col('quantity')), 'totalSales'] ], group: ['productID'], order: [[sequelize.literal('totalSales'), 'DESC']], // 需要返回完整商品信息则保留以下include配置,不需要可删除 include: [{ model: Product, attributes: ['id', 'name'] // 按需指定要返回的商品字段 }], raw: true // 不需要Sequelize实例可开启,直接返回纯JS对象 });
需求2:查询出现频次最高的商品
统计每个productID在表中出现的次数,倒序排序后取第一条即可:
const topFrequencyProduct = await OrderItem.findOne({ attributes: [ 'productID', [sequelize.fn('COUNT', sequelize.col('productID')), 'orderCount'] ], group: ['productID'], order: [[sequelize.literal('orderCount'), 'DESC']], // 需要返回完整商品信息则保留以下include配置,不需要可删除 include: [{ model: Product, attributes: ['id', 'name'] }], raw: true });
注意事项
- 如果存在销量/频次并列第一的情况,将
findOne替换为findAll,再补充having条件筛选数值等于最大值的条目即可。 - 代码中字段名如果和你的实际业务定义不一致,替换为对应字段名即可。
内容的提问来源于stack exchange,提问作者eliezra236
相关产品推荐
相关产品推荐

