我想要一种一对多的关系,其中对于每个父母,一个或零个孩子被标记为“最喜欢的”。然而,并不是每个父母都会有孩子。(将家长视为本网站上的问题,将孩子视为答案,将最喜欢的视为已接受的答案。)例如,
TableA
Id INT PRIMARY KEY
TableB
Id INT PRIMARY KEY
Parent INT NOT NULL FOREIGN KEY REFERENCES TableA.Id
Run Code Online (Sandbox Code Playgroud)
在我看来,我可以将以下列添加到 TableA:
FavoriteChild INT NULL FOREIGN KEY REFERENCES TableB.Id
Run Code Online (Sandbox Code Playgroud)
或 TableB 的以下列:
IsFavorite BIT NOT NULL
Run Code Online (Sandbox Code Playgroud)
第一种方法的问题在于它引入了一个可为空的外键,据我所知,它不是规范化形式。第二种方法的问题是需要做更多的工作来确保最多只有一个孩子是最喜欢的。
我应该使用什么样的标准来确定使用哪种方法?或者,还有其他我没有考虑的方法吗?
我正在使用 SQL Server 2012。
normalization foreign-key database-design sql-server relational-theory
考虑我有两个表Employee
和Department
下面给出的字段:
员工:
Fname、Minit、Lname、Ssn
Bdate、地址、性别、薪水、Super_ssn、Dno
部门:
Dname
, Dnumber
, Mgr_ssn, Mgr_start_date
Italics and code block
表示表的主键。
在上述情况下,Super_Ssn引用SSN员工,而DNO引用该部的Dnumber。为它们创建 sql 非常简单,首先添加列,然后在形成两个表时更改它们。但是,在插入如下所示的数据时:
insert into employee values('James','E','Borg','888665555','1937-11-10','asda','M',55000,NULL,1);
ERROR: insert or update on table "employee" violates foreign key constraint "dno_ref_dnum_dpt"
DETAIL: Key (dno)=(1) is not present in table "department".
Run Code Online (Sandbox Code Playgroud)
和
insert into sp0090.department values ('Headquarter',1,'888665555','1981-06-19');
ERROR: insert or update on table "department" violates foreign key constraint "department_mgr_ssn_fkey"
DETAIL: Key (mgr_ssn)=(888665555) is not …
Run Code Online (Sandbox Code Playgroud)