原生SQL转换为SQLAlchemy语法后返回结果不一致,如何排查?
错误原因
你的SQLAlchemy代码中cc和cc1两个别名的关联顺序写反了,和原生SQL的JOIN逻辑完全不匹配:
原生SQL的关联顺序为:
- POW表关联
cc1别名,关联条件是p.student_id = cc1.student_id - 用
cc1关联term_course表 - 最后用term_course表关联
cc别名
但你的代码中是先用POW表关联cc别名,再关联term_course,最后关联cc1别名,关联逻辑错误导致返回结果条数不一致。
修正后的代码
def get(self, pow_id): try: cc = aliased(CompletedCourse) cc1 = aliased(CompletedCourse) p = aliased(POW) tc = aliased(TermCourse) sc = aliased(SpecializationCourse) results = p.query\ .join(cc1, cc1.student_id == p.student_id)\ .join(tc, tc.id == cc1.term_course_id)\ .join(cc, cc.term_course_id == tc.id)\ .join(sc, and_(sc.course_id == tc.course_id, sc.specialization_id == p.specialization_id), isouter=True)\ .filter(p.id == pow_id)\ .all() print(results) return {}, 200 except Exception as e: raise Exception(f"查询失败: {str(e)}")
调试技巧
你可以通过打印SQLAlchemy生成的原生SQL来快速校验逻辑是否正确:print(str(results.statement.compile(compile_kwargs={"literal_binds": True})))
内容的提问来源于stack exchange,提问作者RuSs
相关产品推荐
相关产品推荐

