I am having trouble adding a check constraint to a table.
Here is the context.
- "Account" and "Category" are two tables each related by a foreign key to the table "Budget" but are otherwise independant
- table "Operation" is related to both "Account" and "Category" by two foreign keys
=> I would like to be sure that they both reference the same item of "Budget" so that : for each operation, account.budget_id == category.budget_id.
How can I manage that with a constraint on my database ? or is there a way to prevent this diamond shape in my database design while keeping account and category independant ?
What I tried :
CONSTRAINT category_and_account_are_from_same_budget CHECK
(
(
SELECT cat.budget_id FROM operation op INNER JOIN category cat ON (op.category_id=cat.id)
except
SELECT acc.budget_id FROM operation op INNER JOIN account acc ON (op.account_id=acc.id)
) IS NULL
)
but
- that didn't feel like an elegant way to do it
- and anyway... "ERROR: cannot use subquery in check constraint"
thanks for your help !