简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM