Search code examples
mysqldatabasedatabase-designdatabase-administration

In M:N database relationship it's better to reference by a composite PK or two foreign keys


I have a database that involves a table called U and a table called P .

table U
  U_Id primary key.

table P
P_Id primary key

There is many to many relationship between the two tables.

I have two ways to create relationship between the two table:

1) create a new table that contains a composite Primary Key (U_Id,P_Id)

2) create a new table that contains references from U table and P table as foreign keys.

(U_id and P_id as foreign keys )

 Third_Table

 U_id FK not null

 P_Id FK  not null

What the better option?


Solution

  • Options 1 and 2 aren't opposed. Your relationship table will contain U_Id and P_Id as foreign keys, and the combination of these two columns should at least be marked as a unique key, if not a primary key.

    Some DB designers prefer to introduce a surrogate identifier as primary key. Others (including myself) prefer to use the combination of foreign keys as the primary key.