1

我有一个表 School 和一个表 Teacher 具有一对多的关系。但是,一位老师是校本,只有一位老师可以是校本。于是想到了在 School 表中保存教师 id(原理)如下:

CREATE TABLE School (
    ID INT PRIMARY KEY,
    Name VARCHAR(40),
    PrincipleID INT FOREIGN KEY REFERENCES Teacher.ID
)

CREATE TABLE Teacher (
    ID INT PRIMARY KEY,
    Name VARCHAR(40),
    SchoolID INT FOREIGN KEY REFERENCES School.ID
)

我知道我可以在学校表中丢失外键引用,但这不是一个选择。

我应该在创建表后进行引用吗?如果是,如何?

4

4 回答 4

3

另一种解决方案是创建一个新表,假设 SchoolsPrinciples 只有两个字段:

CREATE TABLE SchoolsPrinciples
(
  SchoolId int,
  TeacherId int,
  CONSTRAINT uc_SchoolTeacher UNIQUE (SchoolId, TeacherId)
)

一个 UNIQUE 约束让您每所学校只获得一名教师。

于 2012-06-19T20:32:20.327 回答
2

构建表时,您需要将约束添加为单独的 alter 语句。另请注意,在创建外键时,您应该只指定表名,而不是引用的列(该列由主键隐含)。

CREATE TABLE School (
    ID INT PRIMARY KEY,
    Name VARCHAR(40),
    PrincipleID INT);

CREATE TABLE Teacher (
    ID INT PRIMARY KEY,
    Name VARCHAR(40),
    SchoolID INT 
      CONSTRAINT FK_Teacher_School 
      FOREIGN KEY REFERENCES School);

ALTER TABLE School add
    CONSTRAINT FK_School_Teacher 
    FOREIGN KEY (PrincipleID) REFERENCES Teacher;

添加数据时,您需要将 PrincipleID 字段设置为单独的更新:

insert into School (ID, Name)
values (1, 'Blarg Elementary');

insert into Teacher (ID, Name, SchoolID)
values (1, 'John Doe', 1),
       (2, 'Bob Smith', 1),
       (3, 'Adam Walker', 1);

update School set PrincipleID = 2 where ID = 1;
于 2012-06-19T20:27:42.757 回答
1

而是IsPrincipal在桌子上放一个布尔值。Teacher或者添加第三个关系表

CREATE TABLE SchoolPrincipals (
  INT SchoolID PRIMARY KEY FOREIGN KEY REFERENCES School.ID,
  INT TeacherID FOREIGN KEY REFERENCES Teacher.ID
)

保持一切整洁,没有痛苦的删除逻辑。

于 2012-06-19T20:23:36.097 回答
1

您可以将教师表中的一列作为

  1. IsPrincipal其中只有一行具有 jonnyGold 所指的 true 值,

          This can be checked by triggers.
                        OR
          You can use filtered index if using Sql Server 2008.
               Create unique filtered index where SchoolID, IsPrincipal 
               is NOT NULL and are unique
    
  2. 老板,这将包含主体 ID,因此employee manager relationship在您的情况下创建不适合。

CREATE TABLE EmpManager ( TeacherID int SchoolID int IsPrincipal bit ) 并使用过滤索引或触发器来处理场景。

编辑:

CREATE TABLE [dbo].[Teacher](
    [ID] [int] NOT NULL primary key,
    [Name] [varchar](40) NULL,
    [SchoolID] [int] NULL,
) 
GO

CREATE TABLE [dbo].[School](
    [ID] [int] NOT NULL primary key,
    [Name] [varchar](40) NULL,
    [PrincipleID] [int] NULL,
)
GO

ALTER TABLE [dbo].[Teacher]  WITH CHECK ADD  CONSTRAINT [FK_Teacher_School] FOREIGN KEY([SchoolID])
REFERENCES [dbo].[School] ([ID])
GO

ALTER TABLE [dbo].[School]  WITH CHECK ADD  CONSTRAINT [FK_School_Teacher] FOREIGN KEY([PrincipleID])
REFERENCES [dbo].[Teacher] ([ID])
GO

在此处输入图像描述

更好的设计应该是ADC建议的

在此处输入图像描述

于 2012-06-19T20:27:32.853 回答