jio jio - 4 months ago 37
SQL Question

How to add two Foreign keys from same column in MYSQL

I am new in Database field and My database is MYSQL. I have two tables (customer & transaction) which ID column in customer table is Primary key and
transaction table has sender & receiver columns.
I want to make sender and receiver columns Foreign key which are references from ID in customer table.
If it is possible, how can I do it?

Answer

Yes, you can use a primary key of one table in other table as foreign key two times.

you can do in this way.

first foreign key constraint for sender column

ALTER TABLE transaction
ADD CONSTRAINT fk_sender
FOREIGN KEY (sender)
REFERENCES customer(ID)

Second foreign key constraint for receiver column

ALTER TABLE transaction
ADD CONSTRAINT fk_receiver 
FOREIGN KEY (receiver)
REFERENCES customer(ID)