【问题标题】:Converting raw sql to sql alchemy not giving the same results将原始 sql 转换为 sql alchemy 没有给出相同的结果
【发布时间】:2021-12-15 23:07:26
【问题描述】:

我正在尝试将 sql 查询转换为 sqlalchemy 的语法,但没有得到相同的结果。 sql 查询返回我需要的四个测试行,而 python 只返回两个。我的语法有问题吗?

SQL 查询:

SELECT * FROM POW p
    JOIN completed_course cc1 on p.student_id = cc1.student_id
    JOIN term_course tc on cc1.term_course_id = tc.id
    JOIN completed_course cc on tc.id = cc.term_course_id
    LEFT JOIN specialization_course sc on tc.course_id = sc.course_id 
       AND sc.specialization_id = p.specialization_id
    WHERE p.id = 1;

Flask SQLAlchemy:

    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(cc, cc.student_id == p.student_id)\
            .join(tc, tc.id == cc.term_course_id)\
            .join(cc1, cc1.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("")

【问题讨论】:

  • 我在 SQLAlchemy 中看不到该语句 WHERE p.id = 1
  • 过滤器应该可以解决我认为的问题。我确实把它放在了错误的位置,我想通了并且即将更新问题,但现在它导致两个条目而不是我应该得到的四个。

标签: sql flask flask-sqlalchemy


【解决方案1】:

如果你想要如下代码,你可以使用数据库连接:

conn = mysql.connect()
cursor =conn.cursor()

sql_query = """SELECT * FROM POW p
    JOIN completed_course cc1 on p.student_id = cc1.student_id
    JOIN term_course tc on cc1.term_course_id = tc.id
    JOIN completed_course cc on tc.id = cc.term_course_id
    LEFT JOIN specialization_course sc on tc.course_id = sc.course_id 
       AND sc.specialization_id = p.specialization_id
    WHERE p.id = 1;"""

cursor.execute(sql_query)
result = cursor.fetchall()

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多