简体   繁体   English

SQLAlchemy 2 列具有相同的外键 1 关系 - 或查询?

[英]SQLAlchemy 2 columns with same foreign key 1 relationship - OR query?

I have two tables teams and matches (has more columns than shown but these are enough for this example):我有两个表teamsmatches (列比显示的多,但对于这个例子来说这些就足够了):

class Teams(DBBase):
    __tablename__ = 'teams'
    team_id = Column(
        sqlalchemy.INTEGER,
        primary_key=True,
        autoincrement=False)
    sport_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("sports.sport_id"),
        index=True)
    team_type_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("team_types.team_type_id"),
        index=True)
    country_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("countries.country_id"),
        index=True)

class Matches(DBBase):
    __tablename__ = 'matches'
    match_id = Column(
        sqlalchemy.INTEGER,
        primary_key=True,
        autoincrement=False)
    team_0_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("teams.team_id"),
        index=True)
    team_1_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("teams.team_id"),
        index=True)
    venue_id = Column(
        sqlalchemy.INTEGER,
        sqlalchemy.ForeignKey("venues.venue_id"),
        index=True)

I would like to be able to access all of a team's matches, whether they are team_0 or team_1 (think home or away).我希望能够访问团队的所有比赛,无论是team_0还是team_1 (想想主场还是客场)。

In raw SQL I could do something like:在原始 SQL 中,我可以执行以下操作:

SELECT * FROM matches WHERE team_0_id = 'insert team id here' OR team_1_id = 'insert team id here'

or I think even more optimally (speedwise):或者我认为更优化(快速):

SELECT * FROM matches WHERE team_0_id = 'insert team id here' 
UNION
SELECT * FROM matches WHERE team_1_id = 'insert team id here'

Now I am wondering what is the correct (if there is one) way to create a relationship on my Teams class?现在我想知道在我的Teams class 上创建relationship的正确(如果有的话)方法是什么?

I came up with the following:我想出了以下内容:

matches = relationship('Matches', primary_join="or_(Teams.team_id==Matches.team_0_id, Teams.team_id==Matches.team_1_id")

However this won't make use of UNION .但是,这不会使用UNION I also wondered if this is perhaps just bad table/DB design and I should have some sort of association table between matches and teams instead?我还想知道这是否可能只是糟糕的表/数据库设计,而我应该在比赛和球队之间建立某种关联表?

You can use union here, via the ORM's Query.union你可以在这里使用联合,通过 ORM 的Query.union

home_query = session.query(Matches).filter(Matches.team_0_id == 1)

away_query = session.query(Matches).filter(Matches.team_1_id == 1)

all_matches_where_team_participated = home_query.union(away_query).all()

Where session is created from sessionmaker其中session是从sessionmaker创建的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM