我的桌子是:
student
{ Student_id 作为主键,firstName,lastName };teacher
{ Teacher_id 作为主键,firstName,lastName };course
{course_id 作为主键,courseName,学分,teacher_id(来自教师表的外键)}class
{ class_id 作为主键,roomNumber,教师_id 来自教师的外键,course_id 来自课程的外键 }classStudent
{ Student_id 来自学生的外键,class_id 来自班级的外键 }我想检索
courseName
、教师的名字和姓氏、特定学生 ID 的房间号。
我的数据库:
CREATE TABLE `student`
(
`student_id` int(10) NOT NULL,
`firstName` varchar(20) NOT NULL,
`lastName` varchar(20) NOT NULL,
`phone_number` int(8) NOT NULL,
`Email` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `teacher`
(
`teacher_id` int(10) NOT NULL,
`firstName` varchar(20) NOT NULL,
`lastName` varchar(20) NOT NULL,
`phone_number` int(8) NOT NULL,
`Email` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `course`
(
`course_id` varchar(10) NOT NULL,
`Course_Name` varchar(20) NOT NULL,
`Description` varchar(100) NOT NULL,
`credits` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `class`
ADD PRIMARY KEY (`class_id`),
ADD KEY `classTeacher` (`teacher_id`),
ADD KEY `classCourse` (`course_id`);
ALTER TABLE `classstudent`
ADD PRIMARY KEY (`class_id`,`student_id`),
ADD KEY `studentClass` (`student_id`);
-- Constraints for table `class`
--
ALTER TABLE `class`
ADD CONSTRAINT `classCourse`
FOREIGN KEY (`course_id`) REFERENCES `course` (`course_id`)
ON UPDATE CASCADE,
ADD CONSTRAINT `classTeacher`
FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`teacher_id`);
--
-- Constraints for table `classstudent`
--
ALTER TABLE `classstudent`
ADD CONSTRAINT `classstudent_ibfk_1`
FOREIGN KEY (`class_id`) REFERENCES `class` (`class_id`),
ADD CONSTRAINT `studentClass`
FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`);
ALTER TABLE `classstudent`
ADD PRIMARY KEY (`class_id`,`student_id`),
ADD KEY `studentClass` (`student_id`);
我也是堆栈溢出的新手,所以请告诉我是否有关于我的问题的任何说明。
Select course.courseName, teacher.firstName, teacher.lastName, class.roomNumber
from student
inner join classStudent
on student.student_id=classStudent.student_id
inner join class
on classStudent.class_id = class.class_id
Inner join course
On class.course_id = course.course_id
Inner join teacher
On course.teacher_id = teacher.teacher_id
Where student.student_id = ?