Node-Express结合Sequelize使用findAndCountAll查询产品count计数错误
问题原因
该计数异常是Sequelize findAndCountAll 关联查询的通用特性导致:
- 你当前查询关联了
ProductImages这类一对多关系表,SQL执行时会默认做左连接操作,若1条产品记录对应3张产品图片,连接后的结果集会生成3条重复的主表行数据 findAndCountAll默认统计的是连接后结果集的总行数,而非去重后的主表独立记录数,因此会返回和实际主表数据量不符的count值
修复方案
方案1:添加去重计数参数(最简便)
直接在查询配置中新增distinct: 'id'参数,指定Sequelize按主表Product的主键ID去重统计数量,修改后代码如下:
let product = await model.Product.findAndCountAll({ where:condition, attributes:['id' , 'product_name' , 'description' , 'model_information' , 'brand', 'ProductWarrenty' , 'WarrentyDuration' , [price ,'price']], distinct: 'id', // 新增该行,按主表主键去重计数 include:[{ model:model.Category,as:'productcategory' } , { model:model.SubCategory, as:'ProductSubCategory' } , { model:model.ProductImages,as:'product_images' }], offset: offset, limit: 14, order: [sorting] })
方案2:拆分一对多关联查询
如果关联的子表数据量较大,也可以给一对多类型的关联项添加separate: true参数,让Sequelize单独查询子表数据不走连接,从根源避免主表记录被重复计数,修改关联配置如下:
include:[{ model:model.Category,as:'productcategory' } , { model:model.SubCategory, as:'ProductSubCategory' } , { model:model.ProductImages, as:'product_images', separate: true // 单独查询产品图片表,不与主表join }]
内容的提问来源于stack exchange,提问作者Ejaz khan
相关产品推荐
相关产品推荐

