拆分MySQL并进行比较

时间:2015-12-03 12:35:25

标签: mysql

我遇到一个问题,我不知道如何解决它,我是SQL的初学者。

我想显示与教师姓名具有相同FirstName的所有学生的名字。在数据库中,教师的名称是单个字段,但包含2个逻辑字段(FirstName和LastName)

这是我的数据库格式

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)
    );

1 个答案:

答案 0 :(得分: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(非姓氏),并且教授字段包含“Jacques Dupont”(例如)其中Jacques是FirstName而Dupont是LastName的值,那么请尝试这个(使用SUBSTRING_INDEX函数获取教授的FirstName):

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