数据库 bool 属性或 FK 到定义表?

标签 database data-modeling

在我审查过的遗留代码中,我发现了一个数据模型,它创建了相关属性的 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/

相关文章:

mysql - "sensor system"的最佳数据库设计

ios - 当一个持久存储为只读时,核心数据关系没有反转?

mysql - 使用 phpmyadmin 导出/导入 mysql 数据库

ruby-on-rails - 使用 Heroku Web 界面,如何将 PG 数据库从 Heroku 导出为 CSV 文件?

java - Solr 返回 'oldest' 条记录而不是 'newest' ; 'Rows' 和 'Start' 参数

cassandra - cassandra 中的 Instagram 时间轴数据模型

database - Cloud Firestore 深度获取子集合

mysql - 数据库必须是 "perfect"吗?

java - 如何保持数据库中的数据处于 Activity 状态

sql - 车辆数据归一化