I have three tables, table A has a unique primary key that is auto-incremented, and the other two (table B and C) have primary keys that have a foreign key constraint that ties them to the first tables primary key.
I want to make a constraint that maintains that for all rows in the second and third tables they cannot contain any duplicate, and for all records in table A there is a matching record in B or C.
So basically a record of type A can be a type B or C and must be one of B or C.
Is there away to make this constraint without triggers in MySQL? or are triggers necessary?
Thanks for any help.
You can use a “type” table:
with exactly 2 rows (as many as the different subtype tables you need:
The supertype table (that includes a column that references “Type”):
The subtype tables (that are now referencing the combination of A’s Primary key and type_code:
The above would work fine, if only MySQL had implemeneted
CHECKconstraints. But it hasn’t. So, to be absolutely sure that all your specifications are enforced, and not'B'type data is inserted inCtable, you’ll have to add 2 more “type” tables (and remove the useless in MySQLCHECKconstraints):with exactly 1 rows each:
and the additional FKs:
With these constraints, every row of table A, will be either of type B or C and it will be in the respective table (B or C) and never in both.
If you also want to ensure that they will be in exactly one table (and never in neither B nor C), that should be taken care when inserting in A (all insertions should be done with a transaction that enforces that requirement).