问题
If I define tables a
and b
as follows:
CREATE TABLE a(i integer);
ALTER TABLE a ADD CONSTRAINT pkey_a PRIMARY KEY (i);
CREATE TABLE b(j integer);
ALTER TABLE b add CONSTRAINT fkey_ij FOREIGN KEY (j)
REFERENCES a (i) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE;
INSERT INTO a(i) VALUES(1);
And then do the following:
START TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO b(j) VALUES(2);
INSERT INTO a(i) VALUES(2);
COMMIT;
It produces the error below. Why is SET CONSTRAINTS
not having the desired effect?
ERROR: insert or update on table "b" violates foreign key constraint "fkey_ij"
SQL state: 23503 Detail: Key (j)=(2) is not present in table "a".
回答1:
For starters, only DEFERRABLE
constraints can be deferred.
But that won't help your case because, FK constraints cannot be bent this way at all. Per documentation:
Referential actions other than the
NO ACTION
check cannot be deferred, even if the constraint is declared deferrable.
Reverse the sequence of your INSERT
statements.
Related:
- Constraint defined DEFERRABLE INITIALLY IMMEDIATE is still DEFERRED?
来源:https://stackoverflow.com/questions/28680817/set-constraints-all-deferred-not-working-as-expected-in-postgresql-9-3