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

SQL Server原生多表统计查询转SQLAlchemy ORM报错如何解决

问题根因

报错是因为你直接在session.query()中指定了ProductionMaster、Barcode的查询字段,SQLAlchemy默认会将这两个表加入FROM子句,导致Tbl_ProductionScan没有被识别为主表,JOIN条件中引用tbl_ProductionScan.serial_no时无法绑定。

修正方案

你只需要通过select_from显式指定主表为ProductionScan即可,生成的SQL就会和你手写的原生SQL结构完全一致,修正后代码如下:

result = (
    session.query(ProductionMaster.article, Barcode.size, sa.func.count(Barcode.size))
    # 显式指定主表,仅保留ProductionScan在FROM子句
    .select_from(ProductionScan)
    # 按原生SQL顺序关联Barcode
    .join(Barcode, Barcode.serial_no == ProductionScan.serial_no)
    # 再关联ProductionMaster
    .join(ProductionMaster, ProductionMaster.prod_code == Barcode.prod_code)
    .filter(
        sa.and_(
            ProductionScan.date >= "2021-08-01 08:00:00",
            ProductionScan.date <= "2021-08-25 08:00:00",
            ProductionMaster.article.like("%3780%black%"),
        )
    )
    .group_by(ProductionMaster.article, Barcode.size)
    .all()
)

补充说明

注意确认ProductionScan模型的日期字段和表的prod_date列映射正确,如果模型字段名和表列名不一致,记得在filter中使用正确的模型字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:27:08