I have two “child” tables which reference the same “parent” table. Is there a way to only allow the parent tables Primary Key
to be referenced by at-most one of the “child” tables at any time. In practice, the two “child” tables contain different data and therefore it is a requirement that they be separate as otherwise NULL
values would be present if they were to be merged into one large table.
For example:
Take the parent PK (id_primary
) of 1, it can only be referenced (FK) by child_a
or child_b
, but not both.
CREATE TABLE `parent` (
`id_primary` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id_primary`));
CREATE TABLE `child_a` (
`id_primary` INT UNSIGNED NOT NULL,
`data` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id_primary`),
FOREIGN KEY (`id_primary`)
REFERENCES `parent` (`id_primary`)
ON UPDATE CASCADE
ON DELETE CASCADE);
CREATE TABLE `child_b` (
`id_primary` INT UNSIGNED NOT NULL,
`data` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id_primary`),
FOREIGN KEY (`id_primary`)
REFERENCES `parent` (`id_primary`)
ON UPDATE CASCADE
ON DELETE CASCADE);
user25257312 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.