How do you effectively model inheritance in a database?

后端 未结 9 1486
南旧
南旧 2020-11-22 05:37

What are the best practices for modeling inheritance in databases?

What are the trade-offs (e.g. queriability)?

(I\'m most interested in SQL Server and .NET,

相关标签:
9条回答
  • 2020-11-22 06:22

    You would normalize of your database and that would actually mirror your inheritance. It might have performance degradance, but that's how it is with normalizing. You probably will have to use good common sense to find the balance.

    0 讨论(0)
  • 2020-11-22 06:22

    repeat of similar thread answer

    in O-R mapping, inheritance maps to a parent table where the parent and child tables use the same identifier

    for example

    create table Object (
        Id int NOT NULL --primary key, auto-increment
        Name varchar(32)
    )
    create table SubObject (
        Id int NOT NULL  --primary key and also foreign key to Object
        Description varchar(32)
    )
    

    SubObject has a foreign-key relationship to Object. when you create a SubObject row, you must first create an Object row and use the Id in both rows

    EDIT: if you're looking to model behavior also, you would need a Type table that listed the inheritance relationships between tables, and specified the assembly and class name that implemented each table's behavior

    seems like overkill, but that all depends on what you want to use it for!

    0 讨论(0)
  • Note that some database engines already provides inheritance mechanisms natively like Postgres. Look at the documentation.

    For an example, you would query the Person/Employee system described in a response above like this:

      /* This shows the first name of all persons or employees */
      SELECT firstname FROM Person ; 
    
      /* This shows the start date of all employees only */
      SELECT startdate FROM Employee ;
    

    In that is your database's choice, you don't need to be particularly smart !

    0 讨论(0)
提交回复
热议问题