在我审查过的遗留代码中,我发现一个数据模型创建了相关属性的布尔字段,其中只有一个属性为真。例如:
create table MyTable (
id int primary key not null,
// more fields...
has_x bool not null,
has_y bool not null
);
这是愚蠢的,因为它允许潜在的不一致的数据,如果两者都设置为真。我试图向技术人员(但非开发人员)用户解释,但不确定如何解释为什么当原始设计"有效"时,将定义改为1对多关系是合适的。
create table Attributes ( -- contains "x" and "y" records.
id int primary key not null,
name varchar(100) not null
);
create table MyTable (
id int primary key not null,
// more fields
attribute_id int not null foreign key references Attributes(id)
);
这些数据建模模式是否有一个术语?
您正在考虑数据库规范化。
但是,您可以通过实现CHECK
约束来确保一致性,该约束将只允许在任何时候将一个布尔字段设置为true。