简体   繁体   English

MySQL中复合主键的外键关系

[英]Foreign key relationship with composite primary keys in MySQL

Which is the best way to create a relationship between two tables when referenced table has a composite primary key?当引用的表具有复合主键时,在两个表之间创建关系的最佳方法是什么?

table1{
   id,
   name
}

table2{
   id1,
   id2,
   name
}PrimaryKey(id1, id2)

The only way is using both keys:唯一的方法是使用两个键:

alter table t add constraint fk_t_id1_id2
    foreign key (id1, id2) references table2(id1, id2);

However, I would encourage you to add an auto-incrementing column to table2 so such relationships can use a single key.但是,我鼓励您向table2添加一个自动递增列,以便此类关系可以使用单个键。

One way is this一种方法是这样

alter table t add constraint fk_t_id1_id2
foreign key (id1, id2) references table2(id1, id2);

As Gordon said, the best option is create an auto incremental ID and make this the primary key.正如戈登所说,最好的选择是创建一个自动增量 ID 并将其设为主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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