Let’s say have have two tables, A and B.
A contains fields: id, a1, a2.
B contains fields: id, b1, b2.
Asume a one to many relationship from table A to B based on the id field.
Now let’s say I want to create a unique constraint on table b that prohibits me from inserting duplicate records based on b1, b2, and a1. Is that possible?
You would have to have a copy of
a1appear inBin order to enforce this as a constraint. If you don’t want this visible to your users, you would create a table (say,_B) that contains all ofBs columns +a1, and then create a view (with suitable insert triggers to populatea1) calledBthat hides this column.You should also create a superkey of
Aoveridanda1, and use a foreign key constraint (possibly withON UPDATE CASCADE) fromBover both of these columns to ensure that this copied column correctly matches the corresponding value inA.Whether you then decide that this should be the only foreign key, or continue to maintain the “correct” one (over just
id) in addition is a matter of taste.E.g.: