I wonder how to solve this problem.
I got two tables
Table1 (t1_prim, t1_int)
with t1_prim as primary key and t1_int not null.
Table2 (t2_prim1, t2prim2, t2_int)
with t2_prim1 and t2_prim2 as primary key and foreign key constraint t2_prim1 references t1_prim.
how can I define a constraint that makes sure, that nobody enters an integer in t2_int that is bigger than the corresponding entry in t1_int?
I tried it like this (doesn’t work because you can’t enter subqueries in check constraint):
CREATE TABLE table2
(t2_prim1 TEXT,
t2_prim2 INTEGER,
t2_int INTEGER NOT NULL,
PRIMARY KEY (t2_prim1, t2_prim2),
FOREIGN KEY (t2_prim1) REFERENCES table1(t1_prim),
CHECK (t2_int2 <= (SELECT t1_int2 FROM table1 WHERE t1_int1=t2_int1)));
And I think there would be another problem if it would work like this. How do I check, that this constraint is still fullfilled when changing t1_int?
Finally found an answer to my question. You can solve the problem by using triggers. Here’s a working example:
Creating the triggers for updating and inserting:
If you have now the following tables:
table1
table2
You get this output:
Error: Input smaller than maximum of all values for t2_int in database!
Error: Input smaller than maximum of all values for t2_int in database!
Error: Input bigger than value in t1_int!
Error: Input bigger than value in t1_int!
Error: Input bigger than value in t1_int!
While those work perfectly well: