首页 > 解决方案 > 如何将一个表连接到另外两个表,每个表都有一个复合主键?

问题描述

我在 MySQL 数据库中有两个表,我想将它们合并到另一个数据库中的一个表中。这些表由四列组成,它们共同构成一个复合主键。以下是其中一张表的示例:

class GamesATP(Base):
    __tablename__ = "games_atp"
    __table_args__ = {"schema": "oncourt",
                      "extend_existing": True}

    ID_T_G = Column(Integer, ForeignKey("oncourt.tours_atp.ID_T"), primary_key=True)
    ID_R_G = Column(Integer, ForeignKey("oncourt.rounds.ID_R"), primary_key=True)
    ID1_G = Column(Integer, ForeignKey("oncourt.players_atp.ID_P"), primary_key=True)
    ID2_G = Column(Integer, ForeignKey("oncourt.players_atp.ID_P"), primary_key=True)

第二个表是相同的保存atp=wtaATP= WTA

我的想法是将两个表中的数据附加到一个新表中,其中的新列tour_id0foratp1for wta。我还将添加一个新match_id列作为主键。

然后构建一个追加查询,我想我需要将两个表之间的关系定义为 2x ForeignKeyConstraint,如下所示:

class MatchesBLG(Base):
    __tablename__ = "matches_blg"
    __table_args__ = (
        ForeignKeyConstraint(
            ["tour_id", "tournament_id", "round_id", "p1_id", "p2_id"],
            [
                "0",
                "oncourt.games_atp.ID_T_G",
                "oncourt.games_atp.ID_R_G",
                "oncourt.games_atp.ID1_G",
                "oncourt.games_atp.ID2_G",
            ]
        ),
        ForeignKeyConstraint(
            ["tour_id", "tournament_id", "round_id", "p1_id", "p2_id"],
            [
                "1",
                "oncourt.games_wta.ID_T_G",
                "oncourt.games_wta.ID_R_G",
                "oncourt.games_wta.ID1_G",
                "oncourt.games_wta.ID2_G",
            ]
        ),
        {"schema": "belgarath", "extend_existing": True},
    )

    match_id = Column(Integer, primary_key=True)
    tour_id = Column(Integer, index=True)
    tournament_id = Column(Integer, index=True)
    round_id = Column(Integer, index=True)
    p1_id = Column(Integer, index=True)
    p2_id = Column(Integer, index=True)

这给了我错误:

ArgumentError: ForeignKeyConstraint on belgarath.matches_blg(tour_id, tournament_id, round_id, p1_id, p2_id) refers to multiple remote tables: 0 and oncourt.games_atp

我有一个偷偷摸摸的怀疑我不应该在同一张桌子上有两个约束,但我在这里无可救药地超出了我的深度。创建连接的最佳方法是什么?

标签: pythonsqlalchemy

解决方案


推荐阅读