2016-06-06 75 views
0

我有两个实体存储,物品。物品存储在存储器中。项目有不同的类型。例如,物品类型是资源,武器。武器具有独特的项目实例特征“损坏”。如何选择数据库结构?

资源没有任何独特的实例特征,并且可以通过增加计数来堆叠到另一个现有实例。

我有倍数的方式来做到这一点:

  1. 全部保存在一个表:storage_items(ID,ITEM_ID,计数,破损)和item_id创建部分指数与条件计IS NOT NULL

  2. 由类型分开成两个表格(storage_resourcesstorage_weapons

  3. 创建两个表storage_items(storage_items_id,ITEM_ID,计数)和items_properties(id,storage_items_id,损坏)。

回答

1

将不同的子类型链接到公用表的一种方法是使用类型代码来区分链接。例如:

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的存储条目。这允许您在保持它们牢固隔离的同时具有不同类型的项目,从而保持数据完整性。

+0

感谢您的回答。 – user3928409