2015-12-03 70 views
0

我有一個問題,我不知道如何解決它,我是SQL中的一個begginer。拆分MySQL並對其進行比較

我想顯示具有相同名字的老師的名字所有學生的名字,在數據庫中的老師的名字是一個單一的領域,但包含了2個邏輯域(名字和姓氏)

這是我的數據庫格式

CREATE TABLE Faculty (
    Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT 
    ,NAME VARCHAR(50) 
    ,Address VARCHAR(60) 
    ,YearFounded YEAR 
    ,Dean VARCHAR(50) 
    ); 

CREATE TABLE Specialty (
    Id INT NOT NULL PRIMARY KEY auto_increment 
    ,IdFaculty INT (11) NOT NULL 
    ,NAME VARCHAR(50) 
    ,FOREIGN KEY (IdFaculty) REFERENCES Faculty(Id) 
    ); 

CREATE TABLE Course (
    Id INT NOT NULL PRIMARY KEY auto_increment 
    ,IdSpecialty INT NOT NULL 
    ,NAME VARCHAR(50) 
    ,TeachingYear INT 
    ,Semester INT 
    ,Professor VARCHAR(50) 
    ,< -- TEACHER 
    FOREIGN KEY (IdSpecialty) REFERENCES Specialty(Id) 
    ); 

CREATE TABLE Student (
    Id INT NOT NULL PRIMARY KEY auto_increment 
    ,< -- STUDENT 
    IdFaculty INT NOT NULL 
    ,IdSpecialty INT NOT NULL 
    ,CurrentYear INT 
    ,StudyGroup VARCHAR(10) 
    ,Semester INT 
    ,Scholarship VARCHAR(2) 
    ,FOREIGN KEY (IdFaculty) REFERENCES Faculty(Id) 
    ,FOREIGN KEY (IdSpecialty) REFERENCES Specialty(Id) 
    ); 

CREATE TABLE StudentData (
    Id INT NOT NULL PRIMARY KEY 
    ,CNP CHAR(13) 
    ,FirstName VARCHAR(30) 
    ,LastName VARCHAR(30) 
    ,Father VARCHAR(50) 
    ,Mother VARCHAR(50) 
    ,Address VARCHAR(200) 
    ,Nationality VARCHAR(50) 
    ); 

CREATE TABLE Grade (
    Id INT NOT NULL PRIMARY KEY auto_increment 
    ,IdStudent INT NOT NULL 
    ,IdCourse INT NOT NULL 
    ,Grade INT 
    ,ExamDate DATE 
    ,FOREIGN KEY (IdStudent) REFERENCES Student(Id) 
    ,FOREIGN KEY (IdCourse) REFERENCES Course(Id) 
    ); 
+0

StudentData沒有外鍵? –

回答

0

考慮到Course.Professor字段包含教授名字和姓氏,我會用這個查詢:

select sd.FirstName from StudentData sd 
LEFT JOIN Student s on sd.Id = s.Id 
LEFT JOIN Specialty special on s.IdSpecialty = special.Id 
LEFT JOIN Course c on special.Id = c.IdSpecialty 
WHERE c.Professor = CONCAT(sd.FirstName, ' ', sd.LastName) 

編輯:

如果您只需要那些具有相同FirstName(沒有名字)的學生爲教授,如果教授字段包含像「雅克·杜邦」(例如)其中雅克名字和杜邦公司是價值觀姓氏然後試試這個(使用SUBSTRING_INDEX函數獲得教授的姓名):

select sd.FirstName from StudentData sd 
LEFT JOIN Student s on sd.Id = s.Id 
LEFT JOIN Specialty special on s.IdSpecialty = special.Id 
LEFT JOIN Course c on special.Id = c.IdSpecialty 
WHERE SUBSTRING_INDEX(c.Professor,' ',1) = sd.FirstName 
+0

非常感謝 –