MySQL 2个外键引用同一个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40400483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
2 foreign keys referencing same table
提问by Najoua
Can I have two foreign keys in the same table that are referencing an other table named profil(same one) ?
我可以在同一个表中有两个外键引用另一个名为 profil(same one) 的表吗?
my table is MailSent, it contains : primary key (Id), date, foreignkey1 (profil_sender), foreignkey2 (profil_receiver)
我的表是 MailSent,它包含:主键 (Id)、日期、外键 1 (profil_sender)、外键 2 (profil_receiver)
采纳答案by Rimon Khan
Add foreign keys (profil_sender_id, profil_receiver_id)
to an existing table (MailSent)
, follow the following steps:
将外键添加(profil_sender_id, profil_receiver_id)
到现有表中(MailSent)
,请按照以下步骤操作:
ALTER TABLE MailSent ADD CONSTRAINT fk_profile_sender_id FOREIGN KEY (profil_sender_id) REFERENCES TABLE-NAME(id);
ALTER TABLE MailSent ADD CONSTRAINT fk_profil_receiver_id FOREIGN KEY (profil_receiver_id) REFERENCES TABLE-NAME(id);
回答by zhou yun
If you want to add foreign keys when create the table, could do like this:
如果要在创建表时添加外键,可以这样做:
create table MailSent(
Id int primary key,
date datetime,
profil_sender int,
profil_receiver int,
CONSTRAINT fk_sender FOREIGN KEY (profil_sender) REFERENCES profil(id),
CONSTRAINT fk_receiver FOREIGN KEY (profil_receiver) REFERENCES profil(id)
)