2014-09-25 100 views
0

我已經記錄了關於這一點,並閱讀其他用戶張貼關於這一點,但在我的情況下,引用應該工作正常:我有幾個表擴展一個「實體」表和一個「關聯「表只引用」實體「表。所以我引用的只是擁有其他表ID的父表。那麼我如何得到以下內容?Postgresql繼承和外鍵引用父表

ERROR: insert or update on table "association" violates foreign key constraint "association_id1_fkey" 
DETAIL: Key (id1)=(1) is not present in table "entity". 

這是我正在使用的模式。

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); 

行是經過正確插入:

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=# 
+0

實體表有記錄嗎? – Sathish 2014-09-25 09:17:48

+0

是的,更新我的問題,包括選擇統計 – 2014-09-25 09:20:18

+0

你需要通過http://www.postgresql.org/docs/9.3/static/tutorial-fk.html – 2014-09-25 09:46:05

回答

0

父表包含來自繼承表中的所有數據。從該表中進行選擇會在繼承的表上執行UNION

比較這些:

SELECT * FROM "entity"; 
SELECT * FROM ONLY "entity"; 

這就是爲什麼繼承不使用更多。

+0

ops!那麼我不能做我想要做的事情嗎?我需要使用一些觸發器來保持完整性? – 2014-09-25 09:43:18

+0

我只是完全避免繼承,除非你(1)有時間去致力於完全理解它,並且(2)有一個令人信服的理由去偏愛標準的關係實踐。它可以有效地使用,但不是經常使用。 – 2014-09-25 09:45:31