首页 > 解决方案 > 继承 PostgreSQL

问题描述

我在 PostgreSQL 下有 2 个表:

作为母表(id、created_at ..)的表属性和继承属性的居住表(表面、房间等)。在母亲表上,我有一个多对多关系表。我在“居住”表中添加了结果。

当我尝试插入带有居住 ID 的“property_table”时,出现 SQL 错误,告诉我 property_id ID 不存在。当我去查看财产或居住表时,它就存在。我想在 property_tag 中插入居住 ID(所以属性),我应该强制插入吗?请帮忙

SQL 模式:

    CREATE TABLE "property"
    (
        id serial NOT NULL,
        created_at timestamp with time zone NOT NULL DEFAULT now(),
        updated_at timestamp with time zone NOT NULL DEFAULT now(),
        address_id int NOT NULL,
        permission int NOT NULL DEFAULT 6,
        user_id int NOT NULL,
        PRIMARY KEY (id),
        FOREIGN KEY (address_id) REFERENCES "address"(id),
        FOREIGN KEY (user_id) REFERENCES "user"(id)
    );
    CREATE TABLE habitation (
            total_surface float,
            living_surface float,
            ground_surface float,
            ground_surface_unity character varying(15) DEFAULT 'm2',
            room integer,
            bedroom integer,
            floor integer,
            level integer,
            year integer
        )  INHERITS (property);
   CREATE TABLE property_tag 
        (                
            tag_id int NOT NULL,
            property_id int NOT NULL,
            PRIMARY KEY (tag_id, property_id),
            FOREIGN KEY (tag_id) REFERENCES "tag"(id) ON DELETE CASCADE,
            FOREIGN KEY (property_id) REFERENCES "property"(id) ON DELETE CASCADE
        );

CREATE TABLE "tag"
            (
                id serial NOT NULL,
                created_at timestamp with time zone NOT NULL DEFAULT now(),
                updated_at timestamp with time zone NOT NULL DEFAULT now(),
                name character varying(127) NOT NULL,
                user_id int NOT NULL,
                color character varying(7) NOT NULL DEFAULT 'A4A4A8',
                PRIMARY KEY (id),
                FOREIGN KEY (user_id) REFERENCES "user"(id) ON DELETE CASCADE
            );

标签: sqldatabasepostgresqlinheritancemany-to-many

解决方案


当您插入表“居住”时,该行物理上仅存在于表“居住”中,而不存在于“属性”中。

您的表“property_tag”引用了表“property”(没有行,因为行在表“居住”中),因此在插入过程中出现错误。

您必须将表“property_tag”中的参考从“property”更改为“habitation”。


推荐阅读