您如何为一个键存储多行数据并保持良好的规范化实践?

How do you store multiple rows of data for a key and also maintain good normalization practices?

假设在一个数据 table 中,您有一个人及其不同类别 (math/science/english) 和不同考试编号 (1、2) 的考试分数。像这样:

Person Math Science
Bob 88 76
Bob 90 99
Joe 48 46
Joe 70 69

通过按列扩展来规范化此 table 会更好吗(因此,我们有一个 math1 和 science1 列以及一个 math2 和 science 2 列,或者只添加一个 row_id 列?

将列扩展为 math1、science1、math2、science2 等并不是“规范化”。这是一个重复组的例子,通常被认为是违反第一范式的。

您说每个人的多行中的每一行都对应于不同的考试。您如何知道每一行对应的是哪项考试?为什么不添加一列 exam_no?

您所描述的是多对多 (m:m) 关系,同时在实现它时手舞足蹈。您的 m:m 介于实体 Persons 和 Subject(类别)之间,每个实体都成为 table。然后,您通过创建第三个 table 来解决 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 见 fiddle。