SQL Alchemy从同一个表中加入多个列

时间:2016-02-10 23:01:09

标签: python sql join sqlalchemy

my $new_x = $x;
$new_x =~ s/pattern1/replacement1/g;

我需要编写一个连接列和团队表的查询,显示本地和远程团队的团队信息。

class Match(Base):
    __tablename__ = 'matches'

    id = Column(Integer, primary_key=True)
    date = Column(Date, nullable=False)
    time = Column(Time, nullable=True)
    league_id = Column(ForeignKey('leagues.id'), nullable=False, index=True)
    league = relationship('League', backref='matches')
    type = Column(enums.matches_types)
    home_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)
    home_team = relationship('Team', foreign_keys=[home_team_id], backref='home_matches')
    away_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)


class Team(Base):
    __tablename__ = 'teams'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    country_id = Column(ForeignKey('countries.id'), nullable=False, index=True)
    country = relationship('Country', backref='teams')

这会返回Session.query(Match.date, Match.home_team.name, Match_away_team.name).joins(Team)

1 个答案:

答案 0 :(得分:7)

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

使用joinedload

可以更轻松地完成此操作
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将使用m加载到与JOIN相同的查询中。

如果您坚持使用明确的.join(),则必须alias Team个实体(未经测试):

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