我有两张Postgres 10表格,这些表格有些相似但远非相同:
MotorVehicles
Id (auto-incrementing int)
PaintColor (varchar; not null)
EngineSize (int; not null)
Capacity (int)
和
Trailers
Id (auto-incrementing int)
PaintColor (varchar; not null)
AttachedVehicle (int; not null; foreign key referring to MotorVehicles Id)
Capacity (int)
两者都是路上的东西,并且有一些共同的属性,虽然一个明显地附着在另一个上(一辆卡车可以有多个预告片 - 至少就我的目的而言 - 预告片本身不应该存在)。
我试图设计一个适用于MotorVehicle
或Trailer
:LicensePlates
的事物表。
LicensePlates
PlateNumber (varchar; not null)
Issuer (varchar)
ExpirationDate (timestamp)
... some kind of reference to the above tables ...
我不确定如何完成LicensePlates
表格,因为MotorVehicles
和Trailers
之间没有唯一标识符(例如,每个人都可以拥有ID号为1的行,这些内容不一样,因此ParentId
}中只能包含LicensePlates
属性。
任何给定的LicensePlate类行必须引用一个 MotorVehicle或Trailer,但不能同时引用两者,而不是两者。但是,给定的MotorVehicle或Trailer 可能有多个牌照(例如,一个来自加拿大,一个来自欧洲国家);甚至根本没有盘子(如果它刚刚出厂,尚未注册或存放)。
我应该如何设计LicensePlates
?我想出了一些选择:
MotorVehicles
和Trailers
合并到一个ThingsOnTheRoad
表中,这样ID就不会发生冲突
LicensePlates
中,将相关表格中的ID保存在一列中,并将其引用的表格保存在另一列中
MotorVehicles
和Trailers
以获得第二个选项的所有好处,但没有任何缺点
那我该怎么做?我还没有其他选择吗?特别是,是否可以设置我上次提到的视图,如果是,如何设置?
(正如你可能已经猜到的那样,这些不是我的真实表格,但他们确实模拟了这段关系的重点。)
答案 0 :(得分:3)
第二种选择是完美的,它被称为多态关系。我在少数铁路应用中广泛使用的概念就是满足这些要求。
简而言之,LicencePlates
表应包含两列,VehicleID
和VehicleType
。 VehicleID
存储MotorVehicles
或Trailers
和VehicleType
的ID的位置可以引用从中引用ID的表。
这种方法有很多优点。
答案 1 :(得分:1)
Postgres只需要inheritance。
基本上,trailers
和movingvehicles
都应该来自另一个表格 - 比如licensablevehicles
。
然后,您可以与两个原始表或licensablevehicles
建立外键关系。