问题
I already documented about this and read other users post about this on so, but in my case the referencing should be working fine: I have several tables extending one "entity" table and an "association" table referencing just "entity" table. So I'm referencing just the parent table which own every other table id. How come I get the following then?
ERROR: insert or update on table "association" violates foreign key constraint "association_id1_fkey"
DETAIL: Key (id1)=(1) is not present in table "entity".
Here is the schema I'm using.
CREATE TABLE entity (
id serial primary key,
created_at int,
updated_at int,
deleted_at int
);
CREATE TABLE association (
id1 int references entity(id) on delete cascade on update cascade,
atype varchar,
id2 int references entity(id) on delete cascade on update cascade,
created_at int,
deleted_at int
);
CREATE TABLE "user" (
first_name varchar(255),
last_name varchar(255)
)INHERITS(entity);
CREATE TABLE "pet" (
name varchar(255)
)INHERITS(entity);
INSERT INTO "user" (first_name) VALUES ('damiano');
INSERT INTO "user" (first_name) VALUES ('francesco');
INSERT INTO "user" (first_name) VALUES ('romolo');
INSERT INTO "pet" (name) VALUES ('baloo');
INSERT INTO "pet" (name) VALUES ('micia');
INSERT INTO "pet" (name) VALUES ('ioria');
INSERT INTO "association" VALUES (1, 'pets', 4, 0, 0);
INSERT INTO "association" VALUES (1, 'pets', 5, 0, 0);
INSERT INTO "association" VALUES (2, 'pets', 4, 0, 0);
INSERT INTO "association" VALUES (2, 'pets', 5, 0, 0);
INSERT INTO "association" VALUES (3, 'pets', 6, 0, 0);
Rows are correctly insert:
testing=# select * from "entity";
id | created_at | updated_at | deleted_at
----+------------+------------+------------
1 | | |
2 | | |
3 | | |
4 | | |
5 | | |
6 | | |
(6 rows)
testing=# select * from "user";
id | created_at | updated_at | deleted_at | first_name | last_name
----+------------+------------+------------+------------+-----------
1 | | | | damiano |
2 | | | | francesco |
3 | | | | romolo |
(3 rows)
testing=# select * from "pet";
id | created_at | updated_at | deleted_at | name
----+------------+------------+------------+-------
4 | | | | baloo
5 | | | | micia
6 | | | | ioria
(3 rows)
testing=#
回答1:
The parent table doesn't contain all the data from the inherited tables. Selecting from that table in effect does a UNION
over the inherited tables.
Compare these:
SELECT * FROM "entity";
SELECT * FROM ONLY "entity";
That's why inheritance isn't used more.
来源:https://stackoverflow.com/questions/26034752/postgresql-inheritance-and-foreign-key-referencing-parent-table