11

如果我有一个类叫做动物,狗和鱼是子类。动物具有称为“颜色”的属性。狗有“尾长”这个属性,鱼没有这个属性。鱼有“重量”这个属性,狗没有这个属性。

所以,我想设计一个数据库来存储这些信息。我应该怎么办?这里有一些想法:

思路一:做一个动物表,表有类型,找什么动物,如果是狗,就从狗表中得到结果。

动物:颜色:字符串类型:int

类型:狗:0 鱼:1

狗:尾巴长度:int

鱼:重量:int

思路2:数据库中只存储Dog表和Fish表,去掉animal表。

Dog: 颜色: String TailLength: int

鱼:颜色:字符串重量:int

4

3 回答 3

12

The two approaches you mentioned:

  • One table representing objects in the entire inheritance hierarchy, with all the columns you'd need for the entire hierarchy plus a "type" column to tell you which subclass a particular object is.
  • One table for each concrete class in your inheritance hierarchy, with duplicated schema.

can be supplemented by two others:

  • One table for each class in your inheritance hierarchy – you now have an Animal table, and subclasses have tables with foreign keys that point to the common set of data in Animal.
  • Generic schema – have a table to store objects, and an attribute table to support any set of attributes attached to that object.

Each approach has pros and cons. There's a good rundown of them here:

Also take a look at these SO topics:

Finally, it should be noted that there are object-oriented databases (aka object databases, or OODBMSes) out there that represent objects more naturally in the database, and could easily solve this problem, though I don't think they're as frequently used in the industry. Here are some links that describe such DBs as compared to relational (and other) DBs, though they won't give you an entirely objective (heh) view on the matter:

于 2010-07-05T16:50:13.963 回答
0

你可以这样尝试:

Animal
    PK animal_id
    FK animal_type
    STRING animal_name (eg. 'Lassie')

AnimalTypes
    PK animal_type
    STRING animal_type_name (eg. 'Dog')

AnimalAttributes
    PK attribute_id
    STRING attribute_name (eg. 'tail length')

AnimalToAttributes
    PK id
    FK animal_id
    FK attribute_id
    INTEGER value (eg. 20)

这样,您可以为每只动物拥有一个或多个属性(由您选择)。

于 2010-07-05T16:29:14.917 回答
0

使用一对零或一对关系正如您所注意到的,在数据​​库模式设计语言中,表称为类 - 子类或超类

   Create Table Animal
    (animalId Integer Primary Key Not null,
     Other columns generic to all animals)

   Create Table Birds
    (BirdId Integer Primary Key Not Null 
     references Animal(AnimalId),
     -- other columns)
于 2010-07-05T16:30:52.793 回答