Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 当无法使用表继承时,如何维护数据库完整性_Sql_Postgresql_Inheritance - Fatal编程技术网

Sql 当无法使用表继承时,如何维护数据库完整性

Sql 当无法使用表继承时,如何维护数据库完整性,sql,postgresql,inheritance,Sql,Postgresql,Inheritance,我有几种不同的组件类型,每种类型都有截然不同的数据规格来存储,因此每种组件类型都需要自己的表,但它们都共享一些公共列。我最关心的是[component.ID],它必须是组件的唯一标识符,而不管组件类型在许多表中是唯一的 第一选择 我的第一个想法是继承,即每个组件类型的表继承一个通用的[component]表 如果组件不存在,则创建表 ID long主键默认值nextval'component_ID_seq', typeID long not null引用componentType ID, man

我有几种不同的组件类型,每种类型都有截然不同的数据规格来存储,因此每种组件类型都需要自己的表,但它们都共享一些公共列。我最关心的是[component.ID],它必须是组件的唯一标识符,而不管组件类型在许多表中是唯一的

第一选择

我的第一个想法是继承,即每个组件类型的表继承一个通用的[component]表

如果组件不存在,则创建表 ID long主键默认值nextval'component_ID_seq', typeID long not null引用componentType ID, manufacturerID long非空引用制造商ID, 零售价格数字检查零售价格>=0.0, purchasePrice数字检查purchasePrice>=0.0, manufacturerPartNum varchar255不为空, isLegacy布尔值默认值为false, 检查零售价>=购买价 ; 如果主板不存在,则创建表 福隆, 长条
继承组件// 外键应该包含子组件的类型,示例本身就说明了这一点

create table component(
    id int generated always as identity primary key, 
    -- or
    -- id serial primary key, 
    type_id int not null,
    general_info text,
    unique (type_id, id)
);

create table subcomponent_1 (
    id int primary key, 
    type_id int generated always as (1) stored,
    -- or
    -- type_id int default 1 check(type_id = 1),
    specific_info text,
    foreign key(type_id, id) references component(type_id, id) 
);

insert into component (type_id, general_info) 
values (1, 'component type 1');

insert into subcomponent_1 (id, specific_info) 
values (1, 'specific info');
注:

update component
set type_id = 2
where id = 1;

ERROR:  update or delete on table "component" violates foreign key constraint "subcomponent_1_type_id_id_fkey" on table "subcomponent_1"
DETAIL:  Key (type_id, id)=(1, 1) is still referenced from table "subcomponent_1".