2016-06-06 77 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