在我审查过的遗留代码中,我发现了一个数据模型,它创建了相关属性的 bool 字段,其中只有一个应该为真。例如:
create table MyTable (
id int primary key not null,
// more fields...
has_x bool not null,
has_y bool not null
);
这很愚蠢,因为如果两者都设置为 true,则可能会出现不一致的数据。我正在尝试向技术人员而非开发人员用户解释,但不确定如何解释为什么当原始设计“有效”时将定义更改为一对多关系是合适的,如下所示.
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)
);
这些数据建模模式有一个术语吗?
最佳答案
您正在考虑 database normalization .
但是,您可以通过实现 CHECK
constraint 来确保一致性这将只允许在任何时候将 bool 字段之一设置为 true。
关于数据库 bool 属性或 FK 到定义表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5781541/