How to make two tables refer to the same object in a database?

Jack Avante :

Excuse the possibly poorly posed question, let me explain.

I have a table: Doctor, and a table: Patient

Doctor and Patient have the same primary key, 'person_id'

A patient can also be a doctor and vice versa, in which case they'd have the same person_id

Is this allowed? What kind of relationship would I use between these tables? Would I allow auto-increment for the primary keys on both? How would I model this in MySQL Workbench?

spencer7593 :

Sounds to me like Doctor and Patient are sub-classes of Person. If having a relationship between the instances of Doctor and Patient is important, I would make person_id in those tables a foreign_key reference to a new person superclass table:

e.g.

CREATE TABLE `person` 
( id            BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'PK person.id'
, ...
) ...

CREATE TABLE `doctor` 
( person_id     BIGINT PRIMARY KEY COMMENT 'PK, FK ref person.id'
, ...
, CONSTRAINT FK_doctor_person FOREIGN KEY person_id REFERENCE person (id) 
    ON UPDATE CASCADE ...
, ...
) ...

CREATE TABLE `patient` 
( person_id     BIGINT PRIMARY KEY COMMENT 'PK, FK ref person.id'
, ...
, CONSTRAINT FK_patient_person FOREIGN KEY person_id REFERENCE person (id)
    ON UPDATE CASCADE ...
, ...
) ...

This is just one possible approach. Without more context about the problem space, what problems we are trying to solve, we can't make a definitive recommendation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194833&siteId=1