考虑到每辆车至少属于一个车主的业务规则(即车主在被分配给车之前就存在)以及表可能会变大的操作约束,我将设计架构如下:
(通用 sql 92 语法:)
CREATE TABLE Cars
(
CarID integer not null default autoincrement,
OwnerID integer not null,
CarDescription varchar(100) not null,
CreatedOn timestamp not null default current timestamp,
Primary key (CarID),
FOREIGN KEY (OwnerID ) REFERENCES Owners(OwnerID )
)
CREATE TABLE Owners
(
OwnerID integer not null default autoincrement,
OwnerName varchar(100) not null,
Primary key(OwnerID )
)
CREATE TABLE HistoricalCarOwners
(
CarID integer not null,
OwnerID integer not null,
OwnedFrom timestamp null,
Owneduntil timestamp null,
primary key (cardid, ownerid),
FOREIGN KEY (OwnerID ) REFERENCES Owners(OwnerID ),
FOREIGN KEY (CarID ) REFERENCES Cars(CarID )
)
我个人不会触及客户端应用程序中的第三个表,而只是让数据库完成工作 - 并保持数据完整性 - 在 Cars 表上使用 ON UPDATE 和 ON DELETE 触发器来填充 HistoricalCarOwners 表每当汽车更换车主(即在 OwnerId 列上提交 UPDATE 时)或汽车被删除时。
使用上述模式,选择当前车主很简单,选择历史车主很简单
select ownerid, ownername from owners o inner join historicalcarowners hco
on hco.ownerid = o.ownerid
where hco.carid = :arg_id and
:arg_timestamp between ownedfrom and owneduntil
order by ...
HTH,文斯