Can a sql-server table have 2 foreign keys ? please descibe with example
Loading
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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajanikant HawaldarPosted Jul 16, 2022, 9:09 AM
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 KumarPosted Jul 17, 2022, 7:58 AM