简体   繁体   中英

sqlalchemy create a foreign key?

I have a composite PK in table Strings (integer id, varchar(2) lang)

I want to create a FK to ONLY the id half of the PK from other tables. This means I'd have potentially many rows in Strings table (translations) matching the FK. I just need to store the id, and have referential integrity maintained by the DB.

Is this possible? If so, how?

This is from wiki

The columns in the referencing table must be the primary key or other candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table.

Let's say you have this:

id | var            
1  |  10            
1  |  11          
2  |  10

The foreign key must reference exactly one row from the referenced table. This is why usually it references the primary key.

In your case you need to make another Table1(id) where you stored the ids and make the column unique/primary key. The id column in your current table is not unique - you can't use it in your situation... so you make a Table1(id - primary key) and make the id in your current table a foreign key to the Table1 . Now you can create foreign keys to id in Table1 and the primary key in your current table is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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