Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign keys referencing the same primary key

Is this okay to have two foreign keys in one table referencing one primary key of other table?

EmployeeID is a primary key in the employee table and appearing as a foreign key twice in the timesheet table.

There will be few admin users filling up timsheets on the behalf of other employees.

In the timsheet table field 'TimsheetFor' will have employeeID of that person who has worked on projects and field 'EnteredBy' or 'FilledBy' will have employeeid of that person who has filled up this timesheet.

Which of the following option is correct?

NOTE: Tables are showing only those fields which are related to this question.

enter image description here

like image 980
user1263981 Avatar asked Jul 01 '12 18:07

user1263981


People also ask

Can I have 2 foreign keys reference the same primary key?

Yes, it is okay to have two fk to the same pk in one table.

Can 2 foreign keys reference the same table?

In scenarios where a table can have relationships with multiple other tables, you will need to add multiple foreign keys to a table. For the Employee table, you need to add foreign keys that reference the primary keys of the Department table and the Insurance table.

Can a foreign primary key be two?

That's impossible. A FOREIGN KEY constraint can only point to one table and each table can only have one PRIMARY KEY constraint.

Can a foreign key be a primary key in the same table?

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied.


1 Answers

I would go with option 1. It is perfectly fine to have two foreign key columns referencing the same primary key column in a different table since each foreign key value will reference a different record in the related table.

I'm sure option 2 would work, but you would essentially have a 1-to-1 relationship between TIMESHEET_TABLE and TIMESHEET_FILLED_BY, making two tables unnecessary and more difficult to maintain.

In fact, if both ENTERED_BY and TIMESHEET_FOR are required in pairs, using option 1 makes far more sense because this is automatically enforced by the database and foreign keys.

like image 88
Kevin Aenmey Avatar answered Sep 28 '22 04:09

Kevin Aenmey