简体   繁体   中英

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) ?

my table is MailSent, it contains : primary key (Id), date, foreignkey1 (profil_sender), foreignkey2 (profil_receiver)

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM