Skip to content
Advertisement

Primary key with two references

I would like that my relation table “In” has a Foreign key SSN which references to two tables, but the SSN is only in one of these two tables. When I do this:

Then the SSN must be in the table patient and patientWithDoD. The SSN should be in one of the two tables, but not both. How can I do this?

Advertisement

Answer

When a column has a non-null value all related foreign key constraints are checked and validated. If the check fails, the row cannot be inserted or updated.

If you have two FKs and you want only one of them to be enforced, then you’ll need to:

  • create two separated nullable columns, one for each FK, and
  • add a CHECK constraint to enforce one and only one is not null.

For example:

Unfortunately, MySQL just recently started to enforce the CHECK constraints (MySQL 8.0.3 if I remember well). If you are using an older version of MySQL, you are out of luck: MySQL will allow you to write the constraint and save it, but won’t enforce it.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement