How to create composite foreign key in mysql?

Member

by gilbert , in category: MySQL , a year ago

How to create composite foreign key in mysql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , a year ago

@gilbert 

To create a composite foreign key in MySQL, you need to follow these steps:

  1. Create the primary key in the parent table (referenced table): CREATE TABLE ParentTable ( FieldA datatype, FieldB datatype, PRIMARY KEY (FieldA, FieldB) );
  2. Create the foreign key in the child table (referring table) using the same field names as in the parent table and referencing the primary key in the parent table: CREATE TABLE ChildTable ( FieldC datatype, FieldD datatype, FieldA datatype, FieldB datatype, FOREIGN KEY (FieldA, FieldB) REFERENCES ParentTable(FieldA, FieldB) );


Note that the data types of the fields in both tables must match. Each field in the child table corresponds to the respective field in the parent table, creating a composite foreign key relationship between them.