Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should foreign keys become table primary key?

I have a table (session_comments) with the following fields structure:

student_id (foreign key to students table)
session_id (foreign key to sessions table)
session_subject_ID (foreign key to session_subjects table)
user_id (foreign key to users table)
comment_date_time
comment

Now, the combination of student_id, session_id, and session_subject_id will uniquely identify a comment about that student for that session subject.

Given that combined they are unique, even though they are foreign keys, is there an advantage to me making them the combined primary key for that table?

Thanks again.

like image 952
Carvell Fenton Avatar asked Mar 30 '10 14:03

Carvell Fenton


People also ask

Should a foreign key be a primary key in another table?

Yes, foreign key has to be primary key of parent table.

Can foreign key be a primary key?

It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.

Can foreign key not be primary key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.

Why foreign key is not recommended?

There's one good reason not to use them: If you don't understand their role or how to use them. In the wrong situations, foreign key constraints can lead to waterfall replication of accidents. If somebody removes the wrong record, undoing it can become a mammoth task.


1 Answers

  1. Making them the primary key will force uniqueness (as opposed to imply it).
  2. The primary key will presumably be clustered (depending on the dbms) which will improve performance for some queries.
  3. It saves the space of adding a unique constraint which in some DBMS also creates a unique index.

Whether you make these three the primary key or not, you will still need some sort of uniqueness constraint to guarantee that a student cannot be associated with the same session and session_subject_id twice. If that scenario is allowed, then you would need to expand your uniqueness constraint out to include another column.

No matter what choice you make, you should absolutely have some sort of uniqueness constraint on the table.

If you are debating as to whether to create a surrogate primary key + a unique constraint on the three columns, I would say that it depends on whether this table will have child tables. If it will, then referencing the surrogate key will be easier and smaller. If it will not, then IMO, the surrogate key does not really give you much and you might as well use the three columns as the PK.

like image 99
Thomas Avatar answered Sep 28 '22 01:09

Thomas