数据库继承建模的最佳实践是什么?
取舍是什么(例如可查询性)?
(我最感兴趣的是SQL Server和.NET,但我也想了解其他平台如何解决这个问题.)
数据库继承建模的最佳实践是什么?
取舍是什么(例如可查询性)?
(我最感兴趣的是SQL Server和.NET,但我也想了解其他平台如何解决这个问题.)
有几种方法可以对数据库中的继承建模.您 Select 哪一种取决于您的需要.以下是几个选项:
Table-Per-Type (TPT)
每个类都有自己的表.基类中包含所有基类元素,从基类派生的每个类都有自己的表,主键也是基类表的外键;派生表的类只包含不同的元素.
例如:
class Person {
public int ID;
public string FirstName;
public string LastName;
}
class Employee : Person {
public DateTime StartDate;
}
将产生如下表格:
table Person
------------
int id (PK)
string firstname
string lastname
table Employee
--------------
int id (PK, FK)
datetime startdate
Table-Per-Hierarchy (TPH)
只有一个表表示所有继承层次 struct ,这意味着其中的几个列可能是稀疏的.添加了一个鉴别器列,告诉系统这是什么类型的行.
考虑到上面的类,您将得到以下表格:
table Person
------------
int id (PK)
int rowtype (0 = "Person", 1 = "Employee")
string firstname
string lastname
datetime startdate
对于行类型为0(Person)的任何行,startdate将始终为空.
Table-Per-Concrete (TPC)
每个类都有自己的完全形成的表,没有对任何其他表的引用.
考虑到上面的类,您将得到以下表格:
table Person
------------
int id (PK)
string firstname
string lastname
table Employee
--------------
int id (PK)
string firstname
string lastname
datetime startdate