因此:
-
每个人都是联系人。
-
有些联系人是用户,有些不是。
-
有些联系人是学生,有些不是。
-
有些联系人是老师,有些不是。
你可以做这种事。
CREATE TABLE ContactType (
ContactType varchar(8) NOT NULL,
CONSTRAINT ContactType_PK PRIMARY KEY CLUSTERED (ContactType)
)
INSERT INTO ContactType (ContactType)
VALUES
('Student'),
('Teacher')
CREATE TABLE Contact (
ContactId uniqueidentifier NOT NULL DEFAULT(NEWSEQUENTIALID()),
ContactType varchar(8) NOT NULL,
CONSTRAINT Contact_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT User_UQ UNIQUE (ContactId, ContactType), -- To allow FK that enforces type from Student, Teacher, etc. tables.
CONSTRAINT Contact_FK_ContactType FOREIGN KEY (ContactType) REFERENCES ContactType (ContactType)
)
CREATE TABLE [User] (
ContactId uniqueidentifier NOT NULL,
Username varchar(32) NOT NULL,
CONSTRAINT User_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT User_UQ_Username UNIQUE (Username),
CONSTRAINT User_FK_Contact FOREIGN KEY (ContactId) REFERENCES Contact (ContactId)
)
CREATE TABLE Student (
ContactId uniqueidentifier NOT NULL,
ContactType AS CAST('Student' AS varchar(8)),
CONSTRAINT Student_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT Student_FK_Contact FOREIGN KEY (ContactId, ContactType) REFERENCES Contact (ContactId, ContactType)
)
CREATE TABLE Teacher (
ContactId uniqueidentifier NOT NULL,
ContactType AS CAST('Teacher' AS varchar(8)),
CONSTRAINT Teacher_PK PRIMARY KEY CLUSTERED (ContactId),
CONSTRAINT Teacher_FK_Contact FOREIGN KEY (ContactId, ContactType) REFERENCES Contact (ContactId, ContactType)
)