【问题标题】:Postgresql inheritance and foreign key referencing parent tablePostgresql继承和外键引用父表
【发布时间】:2014-09-25 17:41:04
【问题描述】:

我已经对此进行了记录并阅读了其他用户关于此的帖子,但在我的情况下,引用应该可以正常工作:我有几个表扩展一个“实体”表和一个“关联”表仅引用“实体”桌子。所以我只引用拥有其他所有表ID的父表。那我怎么会得到下面的呢?

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

【问题讨论】:

标签: postgresql postgresql-9.1


【解决方案1】:

父表包含继承表中的所有数据。从该表中进行选择实际上会对继承的表执行UNION

比较这些:

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

这就是为什么没有更多地使用继承。

【讨论】:

  • 操作!那么我不能做我想做的事吗?我需要使用一些触发器来保持完整性?
  • 我会完全避免继承,除非您 (1) 有时间完全理解它并且 (2) 有令人信服的理由更喜欢它而不是标准的关系实践。它可以有效地使用,但不经常使用。
猜你喜欢
  • 2014-08-13
  • 2013-01-25
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 2012-06-09
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多