且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL炼金术联接来自同一表的多个列

更新时间:2022-12-12 15:25:19

首先,您的代码不起作用的原因是因为SQLAlchemy不知道您是否要通过home_teamTeam >,所以您必须告诉它.此外,您需要两次加入Team,这会使事情变得更加复杂.

First, the reason your code doesn't work is because SQLAlchemy doesn't know whether you want to join to Team via home_team or away_team, so you'll have to tell it. In addition, you'll need to join to Team twice, which further complicates things.

使用 :

matches = session.query(Match).options(joinedload(Match.home_team),
                                       joinedload(Match.away_team))
for m in matches:
    print m.date, m.home_team, m.away_team

m.home_teamm.away_team将使用JOIN在与m相同的查询中加载.

m.home_team and m.away_team will be loaded in the same query as m using a JOIN.

如果您坚持使用显式的.join(),则必须别名 Team实体(未测试):

If you insist on using an explicit .join() you'll have to alias the Team entities (not tested):

home = aliased(Team)
away = aliased(Team)
q = session.query(Match.date, home, away).join(home, Match.home_team) \
                                         .join(away, Match.away_team)
for date, home_team, away_team in q:
    print date, home_team, away_team