我可以在同一个表中有两个引用另一个名为profil(同一个)表的外键吗?
我的表是MailSent,它包含:主键(Id),日期,foreignkey1(profil_sender),foreignkey2(profil_receiver)
答案 0 :(得分:4)
将外键DF.astype(int)
添加到现有表(profil_sender_id, profil_receiver_id)
,请按照以下步骤操作:
(MailSent)
答案 1 :(得分:1)
如果要在创建表时添加外键,可以这样做:
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)
)
答案 2 :(得分:0)
我们可能需要拖曳引用同一张表的外键,并且如在'@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)
)
并从这两个表中进行选择,并使用两个外键将两个表连接起来,请求将如下所示:
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