[英]2 foreign keys referencing same table
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)
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);
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)
)
We can have tow foreign keys referencing the same table, and as mentioned in '@zhou yun' answer to achieve this the table will be like this:我们可以有两个外键引用同一个表,正如“@zhou yun”回答中提到的那样,表将是这样的:
create table MailSent(
Id int primary key,
profil_sender_id int,
profil_receiver_id int,
FOREIGN KEY (profil_sender_id) REFERENCES profil(id),
FOREIGN KEY (profil_receiver_id) REFERENCES profil(id)
)
and to select from this two table and join the two table using the both foreign key the request will be like that :并从这两个表中选择并使用两个外键连接这两个表,请求将如下所示:
SELECT ms.*, ps.first_name as name_sender,pr.first_name as name_reciver
FROM MailSent ms
LEFT JOIN profil ps
ON ms.profil_sender_id= ps.id
LEFT JOIN profil pr
ON ms.profil_receiver_id= pr.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.