由于双主键,无法映射外键

Cannot map ForeignKey due to dual Primary Keys

我正在尝试根据现有数据即时创建 table...但是,我需要的 table 具有双主键。我找不到如何满足这些限制。

即我从以下两个 tables...

开始
self.DDB_PAT_BASE = Table('DDB_PAT_BASE', METADATA, 
    Column('PATID', INTEGER(), primary_key=True),
    Column('PATDB', INTEGER(), primary_key=True),
    Column('FAMILYID', INTEGER()),
)

self.DDB_ERX_MEDICATION_BASE = Table('DDB_ERX_MEDICATION_BASE', METADATA, 
    Column('ErxID', INTEGER(), primary_key=True),
    Column('ErxGuid', VARCHAR(length=36)),
    Column('LastDownload', DATETIME()),
    Column('LastUpload', DATETIME()),
    Column('Source', INTEGER()),
    )

当我尝试以下操作时,它起作用了...

t = Table('testtable', METADATA,
    Column('ErxID', INTEGER(), ForeignKey('DDB_ERX_MEDICATION_BASE.ErxID')),
    )     
t.create()

但是,以下两个都给我错误...

t = Table('testtable', METADATA,
    Column('PATID', INTEGER(), ForeignKey('DDB_PAT_BASE.PATID')),
)
t.create()

t = Table('testtable', METADATA,
    Column('PATID', INTEGER(), ForeignKey('DDB_PAT_BASE.PATID')),
    Column('PATDB', INTEGER(), ForeignKey('DDB_PAT_BASE.PATDB')),
)
t.create()


sqlalchemy.exc.OperationalError: (pymssql.OperationalError) (1776, "There are no primary or candidate keys in the referenced table 'DDB_PAT_BASE' that match the referencing column list in the foreign key 'FK__testtabl__PATID__3FD3A585'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") [SQL: '\nCREATE TABLE [testtable] (\n\t[PATID] INTEGER NULL, \n\tFOREIGN KEY([PATID]) REFERENCES [DDB_PAT_BASE] ([PATID])\n)\n\n']

您指向的 table 有一个 复合 主键,而不是多个主键。因此。您需要创建一个复合外键,而不是指向复合主键每一半的两个外键:

t = Table('testtable', METADATA,
    Column('PATID', INTEGER()),
    Column('PATDB', INTEGER()),
    ForeignKeyConstraint(['PATID', 'PATDB'], ['DDB_PAT_BASE.PATID', 'DDB_PAT_BASE.PATDB']),
)
t.create()