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

Sequelize使用findAndCountAll关联查询时count统计错误是bug吗?

这不是Sequelize的bug,是1对多关联查询场景下的默认统计逻辑导致的。

原因说明

你编写的查询对1:m关联的WorkflowStep做了连表查询,底层生成的SQL会先执行LEFT JOIN,将主表Workflow的每一条记录和关联的所有WorkflowStep子记录做拼接,最终JOIN后的结果行数等于所有匹配的Workflow对应的WorkflowStep记录总和。默认情况下findAndCountAll的count统计的是JOIN后的总行数,因此会出现和rows数组长度不一致的情况。

解决方案

你可以在查询参数中添加distinct: true,让count统计时自动按主表主键去重,即可得到正确的主表记录数,修改后的代码如下:

const results = await Workflow.findAndCountAll({
  limit: limit,
  offset: offset,
  where: { userId: userId },
  include: [ WorkflowStep ],
  distinct: true
});

如果你的Sequelize版本支持,也可以在关联配置中添加separate: true,让关联查询单独执行,避免连表导致的count统计异常:

const results = await Workflow.findAndCountAll({
  limit: limit,
  offset: offset,
  where: { userId: userId },
  include: [{
    model: WorkflowStep,
    separate: true
  }]
});

内容的提问来源于stack exchange,提问作者Jose Raul Perera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:51:02