I have a SQL table that can reference another record in the table as its parent
but should not reference itself. I have attempted to enforce this with a CHECK
constraint but my attempts have failed as the id
is an auto-increment column. Is there any other way to ensure that parent_id <> id
?
My current attempt, which fails with error Check constraint 'not_own_parent' cannot refer to an auto-increment column. (errno 3818)
:
CREATE TABLE `content` (
`id` serial PRIMARY KEY NOT NULL,
`item_id` int NOT NULL,
`nested_item_id` int,
`block_id` int,
`order` int NOT NULL,
CONSTRAINT not_own_parent CHECK (nested_item_id <> id)
);
3
Answers
Don’t put this kind of thing in a constraint. For one thing, you can’t do it directly in MySql. You’d have to use a trigger or something.
Instead:
One way to control auto-generated live values is by using triggers to manage new values.
For example, create instead of insert trigger to control newly generated ID. In triggers, you can make decisions based on the new value.
Here’s a demo of using a trigger to cancel an insert that violates the condition you describe. You must use an AFTER trigger because in a BEFORE trigger the auto-increment value has not yet been generated.