Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Using foreign key as primary key too

I have table 1 with a primary key user_id and table 2 where user_id is a foreign key.

Only 1 record per user_id can exist in table 2, and no record can exist without it.

QUESTION: Can user_id in table 2 be both foreign and primary key at the same time, and if yes, is it a good idea, what are pros/cons?

like image 653
CodeVirtuoso Avatar asked Jan 20 '12 23:01

CodeVirtuoso


People also ask

Can foreign key also be 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. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.

Can 2 foreign keys be Primary Keys?

The FOREIGN KEY constraint differs from the PRIMARY KEY constraint in that, you can create only one PRIMARY KEY per each table, with the ability to create multiple FOREIGN KEY constraints in each table by referencing multiple parent table.

Can something be a primary key and foreign key at the same time?

A Foreign Key is used for referential integrity, to make sure that a value exists in another table. The Foreign key needs to reference the primary key in another table. If you want to have a foreign key that is also unique, you could make a FK constraint and add a unique index/constraint to that same field.

Can I have the same field as primary key and foreign key in mysql?

You can create a column having both keys (primary and foreign) but then it will be one to one mapping and add uniqueness to this column.


1 Answers

Yes, you can do this (and you should, from a database design point of view).

However, consider what it means if user_id is the primary key on table 2. You are in effect saying that each row in table 2 corresponds to a user, but you already have a table where each row corresponds to a user: table 1. This raises the question "why then don't you put all data of table 2 into nullable columns in table 1?". After all, having two tables means you will have to make two queries to get this data instead of one.

Now there are some scenarios where this practice might be a good idea:

  • if you have lots of users but only a few rows in table 2, perhaps the query on table 2 will be only performed rarely; at the same time, you gain storage space and modification speed on table 1
  • it might be possible in the future for the primary key of table 2 to change, while the foreign key remains; if you put all the data in table 1, this modification would most likely break your database model

It can be a good idea, but it depends on the particulars of your application.

like image 112
Jon Avatar answered Oct 07 '22 08:10

Jon