如何解决您如何为一个键存储多行数据并保持良好的规范化实践?
想象一下,在一个数据表中,您有一个人及其不同类别(数学/科学/英语)和不同考试编号(1、2)的考试成绩。像这样:
人 | 数学 | 科学 |
---|---|---|
鲍勃 | 88 | 76 |
鲍勃 | 90 | 99 |
乔 | 48 | 46 |
乔 | 70 | 69 |
通过按列扩展来规范化这个表会更好(所以,我们有一个 math1 和 science1 列以及一个 math2 和 science 2 列,还是只添加一个 row_id 列?
解决方法
将列扩展为 math1、science1、math2、science2 等不会“标准化”。这是重复组的一个例子,通常被认为违反了第一范式。
您说每个人的多行中的每一行都对应不同的考试。你怎么知道每一行参加哪项考试?为什么不添加列 exam_no
?
您所描述的是多对多 (m:m) 关系,同时围绕着实现它。您的 m:m 位于实体 Person 和 Subject(类别)之间,每个实体都变成一个表。然后,您通过创建第三个表来解析 m:m - 称之为考试。
create table persons ( person_id integer generated always as identity,name text
-- other attributes strictly about each person,constraint persons_pk
primary key (person_id)
) ;
create table subjects ( subject_id integer generated always as identity,name text,description text
-- other attributes strictly about each subject,constraint subjects_pk
primary key (subject_id)
) ;
create table exams ( person_id integer,subject_id integer,exam_date date,score integer
-- other attributes strictly about each exam,constraint exams_pk
primary key (person_id,subject_id,exam_date),constraint exams2persons_fk
foreign key (person_id)
references persons(person_id),constraint exams2subject_fk
foreign key (subject_id)
references subjects(subject_id)
) ;
注意:以上仍然是一个非常简化的示例,但应该为解决此类设计问题提供指导。请参阅 worked example 的小提琴。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。