【问题标题】:How to choose database structure?如何选择数据库结构?
【发布时间】:2016-10-06 13:46:24
【问题描述】:

我有两个实体 Storage,Items。物品存放在储藏室中。物品有不同的类型。例如,项目类型是资源、武器。武器具有独特的物品实例特征“损坏”。

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

我有多种方法可以做到:

  1. 将所有内容保存在一个表中:storage_items(id、item_id、计数、损坏)并在item_id 上创建部分索引,条件为 COUNT IS NOT NULL

  2. 按类型将其分成两个表(storage_resourcesstorage_weapons

  3. 创建两个表storage_items (storage_items_id, item_id,count) 和items_properties (id, storage_items_id, 损坏)。

【问题讨论】:

    标签: database postgresql database-design


    【解决方案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 类型。所有 Resource 条目必须在 Storage 中有一个定义为 R 的条目,并且所有 Weapon 条目都必须有一个定义为 W 的 Storage 条目。这允许您拥有不同类型的项目,同时保持它们牢固隔离,保持数据完整性。

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多