將不同的子類型鏈接到公用表的一種方法是使用類型代碼來區分鏈接。例如:
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型。所有資源條目必須在定義爲R的存儲中具有條目,並且所有武器條目必須具有被定義爲W的存儲條目。這允許您在保持它們牢固隔離的同時具有不同類型的項目,從而保持數據完整性。
感謝您的回答。 – user3928409