仅使用 DDL 的解决方案。无触发器:
CREATE TABLE child
( id number NOT NULL,
parent_id number NOT NULL,
allocation number NOT NULL,
我们添加了一些我们需要的列:
child_no number NOT NULL, -- a number from 1 to 3
prev_child_no number NOT NULL, -- previous child number
running_total number NOT NULL, -- running total of allocations
prev_running_total number NOT NULL, -- previous running total
除了你有的限制
-- I guess you already have these two constraints
PRIMARY KEY (id),
FOREIGN KEY (parent_id)
REFERENCES parent (id),
CHECK ( allocation >= 0 ),
我们添加了更多内容,用于子到前子关系:
-- this links a child to the previous one
FOREIGN KEY (parent_id, prev_child_no, prev_running_total)
REFERENCES child (parent_id, child_no, running_total),
-- these 2 constraints enforce that there are
UNIQUE (parent_id, child_no), -- maximum 3 children
CHECK (child_no IN (1,2,3)), -- per parent
-- and this exactly 3 children per parent
CHECK ( child_no = 1 AND prev_child_no = 3
OR child_no > 1 AND prev_child_no + 1 = child_no ),
对于运行总计:
-- this enforces that the running total is correct
CHECK ( child_no = 1 AND running_total = allocation
OR child_no > 1 AND running_total = allocation + prev_running_total ),
-- enforce that it never exceeds 100
CHECK ( running_total <= 100 )
) ;