mysql - 对单个查询中的多个 Join 感到困惑,Sqlalchemy

标签 mysql database sqlalchemy

我试图在 SQLAlchemy 中的单个查询中连接三个表,但无法这样做。 到目前为止我已经做到了:-

Test.query.join(Test.sections).join(QuestionSection.section).all()

我知道这是错误的,但我试图在单个查询中完成它。

这是我的表格:-

问题部分型号:-

class QuestionSection(Dictifiable, db.Model):
    __tablename__ = 'question_section'

    section_id = Column(Integer, ForeignKey('section.id'), primary_key=True)
    question_id = Column(Integer, ForeignKey('question.id'), primary_key=True)

    question = db.relationship('Question', backref='question_section')
    section = db.relationship('Section', backref='question_section')

节表:-

class Section(Dictifiable, db.Model):
    __tablename__ = 'section'

    id = Column(Integer, Sequence('section_id_seq'), primary_key=True)
    test_id = Column(Integer, ForeignKey('test.id'))
    name = Column(String(50))

    test = relationship("Test", back_populates="sections")

    questions = db.relationship('Question',
                                secondary='question_section')

和测试表:-

 id = Column(Integer, Sequence('test_id_seq'), primary_key=True)
    name = Column(String(50))

    sections = relationship("Section", back_populates="test")
    tests = relationship("Corporate", secondary='corporate_test',
                         back_populates='tests')

最佳答案

我明白我做错了什么,我应该这样加入:-

Test.query.join(Test.sections).join(QuestionSection, QuestionSection.section_id == Section.id).all()

关于mysql - 对单个查询中的多个 Join 感到困惑,Sqlalchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205136/

相关文章:

python - SQLAlchemy 循环依赖 - 如何解决?

python - 使用 sql alchemy 查询有一种方法可以遍历表中的所有列

mysql - 为什么在违反唯一键约束而不是主键约束时 MySQL 中会出现自动增量间隙?

database - 融合表适合做网站数据库吗?

sql - 如何交换表中 2 条记录的列值?

python - 如何检查我的 sqlite 列是否不在我的数据框中?

mysql - C客户端程序连接MySQL错误检测

mysql - SQL 连接中的多个条件

python - Eclipse osx 中的 MySQLdb

python - Django 树表的复杂分区和排序