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

Sequelize原生查询部分字段返回null但MySQL直接执行正常的问题求助

Sequelize原生查询部分字段返回null但MySQL直接执行正常的问题求助

我现在遇到两个棘手的问题,想请教各位:

  1. 直接在MySQL客户端执行查询语句时,current_items、total_required_items等字段能返回正确的数值,但用Sequelize执行相同的原生查询后,这些字段却返回null;
  2. 另外我还存在疑惑:数据库里定义的都是数字类型字段,为什么查询结果里部分数值类型会以对象形式返回?

以下是我的代码实现(Node.js/Express + Sequelize):

const queryResult = await sequelize.query(
  `SELECT tbl1.identifier, 
          COUNT(DISTINCT tbl1.item_id) AS item_count,
          tbl2.assigned_items, 
          tbl3.current_items, 
          tbl3.total_required_items,
          tbl3.expected_items_assigned, 
          tbl3.items_required
   FROM data_table_1 tbl1
   LEFT JOIN data_table_3 tbl3 ON tbl1.identifier = tbl3.identifier
   LEFT JOIN (
       SELECT identifier, COUNT(*) AS assigned_items
       FROM data_table_2
       GROUP BY identifier
   ) tbl2 ON tbl1.identifier = tbl2.identifier
   WHERE tbl1.identifier = "${someIdentifier}"
   GROUP BY tbl1.identifier;`,
  { type: QueryTypes.SELECT, logging: console.log, raw: true }
);

const {
  identifier,
  total_required_items,
  current_items,
  expected_items_assigned,
  assigned_items,
  item_count,
  items_required,
} = queryResult[0] || {};

执行后我打印了查询结果:

console.log(queryResult);

得到的输出是:

[
  {
    identifier: 'abc123',
    item_count: 12,
    assigned_items: 2,
    current_items: null,
    total_required_items: null,
    expected_items_assigned: null,
    items_required: null
  }
]

最奇怪的是,我把这段SQL原封不动复制到MySQL客户端执行,current_items、total_required_items这些字段都是有正常数值的,完全不是null!这直接导致我后续的逻辑判断出错,比如这段判断代码:

const canProceed=
  (total_required_items== current_items && item_count> items_required) ||
  total_required_items> current_items||
  identifier== null ||
  identifier== "";

有没有朋友遇到过类似的问题?麻烦帮我分析下可能的原因,非常感谢!


备注:内容来源于stack exchange,提问作者solace

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:14:29