2016-03-02 77 views
6

我試圖從現有數據實時創建表...但是,我需要的表有雙主鍵。我無法找到如何滿足限制。由於雙主鍵無法映射ForeignKey

I.e.我先從下面兩個表...

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'] 

回答

3

您指向的表有一個複合主鍵,而不是多個主鍵。因此。你需要創建一個複合外鍵,而不是指向複合主鍵的每一半的兩個外鍵:

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

美麗。謝謝! – RightmireM