I have 2 tables, referenced through a FK.
users table (id as PK)
cars table (id as PK, userId as FK to users, unique relationship id-userId)
On a third table, I want to record some data from cars.but in case a car is not yet registered, the carId is null.
question: when I update the third table, how can I make sure the car belongs to that user? if I use a trigger on insert for validation, how to make sure the data remains consistent when the cars table is updated?
I add a diagram, to be more explicit.
2
Answers
You can do this check trough a trigger before UPDATE.
LATER EDIT:
As for the second part of your question, "how to make sure the data remains consistent when the cars table is updated" you can do this also via a trigger after update on the cars table:
If you have ON UPDATE CASCADE on the carsId foreign key definition of the contribution table then the trigger is more simple:
The only good solution is a foreign key constraint. Create a (redundand) unique constraint on
cars("userId", id)
and reference that in the foreign key oncontributions
.As long as
contributiobs."carId"
is NULL, the foreign key won’t be enforced.