2 foreign keys referencing same table
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:
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
Add foreign keys (profil_sender_id, profil_receiver_id)
to an existing table (MailSent)
, follow the following steps:
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);