Can a sql-server table have 2 foreign keys ? please descibe with example
Can a table have 2 foreign keys from same table in sql-server ?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Can a sql-server table have 2 foreign keys ? please descibe with example
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Jul 16, 2022, 5:09 AM EDT
For example, 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);
We can have tow foreign keys referencing the same table, 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
Aryan KumarRank #2,431 · 580 reputationPosted Jul 17, 2022, 3:58 AM EDT