How to implement a super class, sub class relationship in the database?

為{幸葍}努か 提交于 2019-11-30 05:19:15

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:

You could try it like this:

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)

This way you can have one or many attributes per animal (it's up to you to choose).

Use a one to zero or one relationship As you note, In database schema design language the tables are called class - sub-class or superclass

   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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!