sqlalchemy 2列具有相同的外键1关系-还是查询?

5lwkijsr  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(399)

我有两张table teams 以及 matches (包含的列比显示的多,但对于本例来说这些就足够了):

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)

我想能够访问一个球队的所有比赛,无论他们是 team_0 或者 team_1 (想回家或离开)。
在原始sql中,我可以执行以下操作: SELECT * FROM matches WHERE team_0_id = 'insert team id here' OR team_1_id = 'insert team id here' 或者我认为更理想的(速度方面):

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

现在我想知道创建一个 relationship 在我的 Teams 上课?
我得出了以下结论:

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

但是这不能利用 UNION . 我还想知道这是否只是糟糕的table/db设计,我应该在比赛和球队之间建立某种关联表?

eoxn13cs

eoxn13cs1#

您可以通过orm的query.union在这里使用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()

哪里 session 是从sessionmaker创建的

相关问题