Philipp Wajeed
Philipp Wajeed

Reputation: 67

Foreign Key relationship using Primary Key of both tables

All users of our system are derived from a main "User" class. Likewise, we want to structure our database in the same way, having one main "user" table, which is joined with the necessary tables for the specific user type, to provide additional user information.

See as an example these three basic tables:

Table "user"
user_id | user_email | user_firstname | user_lastname | ...

Table "employee"
user_id | employee_staff_number | ...

Table "admin"
user_id | admin_permissions | ...

All three tables have the "user_id" column as their primary key, which will obviously always have the same value for same users.

However, I just tried to implement foreign keys, so that a user row cannot exist in the derived tables without the corresponding entry in the main user table. Trying to run the following SQL

ALTER TABLE `employee` ADD CONSTRAINT `fk_employee` FOREIGN KEY (`user_id`) REFERENCES `database_name`.`user`(`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

results in the Error

#1215 - Cannot add foreign key constraint 

Is there even a way to implement this, without introducing a new primary key in the derived tables, to make "user_id" be a regular index in those?

Upvotes: 0

Views: 134

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

Two things to check for:

  • Is user(user_id) declared as the primary key in user?
  • Do user.user_id and employee.user_id have the same type?

You need an index on user(user_id) in order to use it as a foreign key reference. The best way to create such an index is by declaring it to be a primary key.

Upvotes: 2

Related Questions