簡體   English   中英

如何將復合主鍵插入另一個表?

[英]How to insert a composite primary key into another table?

我有一個復合主鍵,我想插入另一個表。

create table courses_instructors
(
courseID int foreign key references Course(C_ID) not null,
instructorID int foreign key references Instructor(I_ID) not null,
primary key (courseID, instructorID), --coourseID and instructorID combined is the composite PK
courseTerm varchar(50) not null,
courseNumber int not null,
courseLocation varchar(50),
courseTime varchar(50),
courseMaxOccupancy int,
courseSeatAvailable int
)

create table courses_students
(
studentID int foreign key references student(S_ID) not null,
courseID int, -- foreign key -- I want this value to the be value that represents the composite PK from the courses_instructors
primary key(studentID, courseID), -- these 2 fields combined would make the composite PK, but with the courseID value I will be able to identify who is the instructor for a course and the other details from the course_instructor table
courseOutcome varchar(50)
)

所有課程都來自一個課程表,其中只包含課程名稱和門徒以及描述。 課程表有一個主鍵,可以唯一標識每個課程。

要引用composit主鍵,Courses_Students表應該同時包含CourseID和InstructorID列。

接着

ALTER TABLE Courses_Students
ADD CONSTRAINT FK_Courses_Students
FOREIGN KEY(CourseID, InstructorID) REFERENCES Courses_Instructors(CourseID, InstructorID)

或者表定義應該是這樣的,

create table courses_instructors
(
courseID int foreign key references Course(C_ID) not null,
instructorID int foreign key references Instructor(I_ID) not null,
primary key (courseID, instructorID), --coourseID and instructorID combined is the composite PK
courseTerm varchar(50) not null,
courseNumber int not null,
courseLocation varchar(50),
courseTime varchar(50),
courseMaxOccupancy int,
courseSeatAvailable int
)

create table courses_students
(
studentID int foreign key references student(S_ID) not null,
courseID int,
instructorId int,
FOREIGN KEY(CourseID, InstructorID) REFERENCES Courses_Instructors(CourseID, InstructorID),
primary key(studentID, courseID, InstructorId),
courseOutcome varchar(50)
)

您可以像前面提到的那樣引用兩列,或者將一個代理鍵(例如標識列或GUID)添加到主表中並引用它 - 它通常表現更好。

course_instructors表是交叉表,其實現了可能容易猜到的課程實體和教師實體之間的mm關系。 幾乎無一例外,我沒有為這樣的表添加代理鍵,原因很簡單,因為這樣的密鑰永遠不會被使用。 典型用戶具有對一個實體或另一個實體的引用,並希望看到與其相關的所有其他實體。 或者有時用戶可以引用這兩個實體,並希望獲得他們關系的詳細信息。

然而,這條規則並非沒有例外,您的用例就是這樣一個例子。 該表不僅表達了兩個實體之間的關系,而且成為了一個實體:一個類提供。 學生將從已發布的課程表和所需的日期/時間中選擇一個班級。 這將通過某種類代碼編號來識別。

此代碼將用於注冊所需的類。 在這種情況下,為交集表創建一個代理鍵是有意義的 - 然后它成為目錄中打印的類代碼。 因此,您將使用此類代碼來引用定義類提供的關系,而不是使用組合鍵。

看起來你已經有了這樣一個復合鍵:course_number字段。 您沒有將其定義為唯一,但它不能唯一地標識組成每個課程的課程,講師,地點和時間的組合嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM