1

桌子

Instructor
    ------------------------------------------------------
    | id | firstname | lastname | subject_id | section_id |
    ------------------------------------------------------
       1    John        Smith        1             1

Subject
    -------------
    | id | name |
    -------------
      1  English
      2   Math

Section
    -------------
    | id | name |
    -------------
     1  Section A

我的查询:

SELECT ins.firstname, ins.lastname,sec.name as "Section Name", sub.name as "Subject"
    FROM instructor as ins
    JOIN section as sec
    JOIN subject as sub
    WHERE ins.section_id = sec.id AND ins.subject_id = sub.id AND ins.id =1

结果:

firstname   lastname    Section Name    Subject 
John    Smith            Section A  English

我的问题是,如果那个讲师约翰史密斯也教数学科目我将如何查询呢?我需要添加新的subject_id吗?这些有什么解决办法吗?

谢谢,

4

2 回答 2

3

您可以添加另一个表用于存储每个讲师的科目,例如

CREATE TABLE Instructor
(
    ID INT,
    InstructorName VARCHAR(30),
    ..... -- other fields here
);

CREATE TABLE Subject
(
    ID INT,
    SubjectNameName VARCHAR(30),
    ..... -- other fields here
);

CREATE TABLE INSTRUCTOR_SUBJECT
(
    RecID INT,
    InstructorID INT,
    SubjectID INT,
    CONSTRAINT tc_pk PRIMARY KEY (RecID),
    CONSTRAINT tc_fk1 FOREIGN KEY (InstructorID) REFERENCES Instructor(ID),
    CONSTRAINT tc_fk2 FOREIGN KEY (SubjectID) REFERENCES Subject(ID)
);
于 2012-11-09T08:02:24.553 回答
0

您现在拥有的是一对多的关系,其中一个讲师只能有一个科目,但任何科目都可以有多个讲师。您想要一个多对多关系,这意味着添加一个只有instructor_id和 的新表subject_id

于 2012-11-09T08:02:33.613 回答