将不同子类型链接到公共表的一种方法是使用类型代码来区分链接。例如:
create table Storage(
ID serial,
ItemType char( 1 ) not null,
..., -- Fields common to all items
constraint CK_StorageType check ItemType in( 'R', 'W' ),
primary key( ID, ItemType )
);
ID 字段本身将是唯一的,因此您可能需要或只想拥有它自己的 PK。您可以改为:
create table Storage(
ID serial,
ItemType char( 1 ),
..., -- Fields common to all items
constraint CK_StorageType check ItemType in( 'R', 'W' ),
primary key( ID ),
constraint UQ_IdItem unique( ID, ItemType )
);
无论哪种方式,为每种类型的项目创建一个单独的表:
create table ResourceItems(
ID int not null,
ItemType char( 1 ) not null,
..., -- Fields unique to Resource items
constraint ResourceItemType check( ItemType = 'R' ),
primary key( ID, ItemType ),
constraint FK_ResourceItem_Storage( ID, ItemType )
references Storage( ID, ItemType )
);
create table WeaponItems(
ID int not null,
ItemType char( 1 ) not null,
..., -- Fields unique to Weapon items
constraint WeaponItemType check( ItemType = 'W' ),
primary key( ID, ItemType ),
constraint FK_WeaponItem_Storage( ID, ItemType )
references Storage( ID, ItemType )
);
因此,您必须将所有存储条目指定为 R 或 W 类型。所有 Resource 条目必须在 Storage 中有一个定义为 R 的条目,并且所有 Weapon 条目都必须有一个定义为 W 的 Storage 条目。这允许您拥有不同类型的项目,同时保持它们牢固隔离,保持数据完整性。